【问题标题】:Looping over text files and calling python script in makefile循环文本文件并在makefile中调用python脚本
【发布时间】:2019-02-08 10:45:05
【问题描述】:

我想在我的 makefile 中检索某个子文件夹中的所有文本文件(目前我刚刚得到一个) 并以每个文本文件作为输入参数循环调用特定的 python 脚本。

这是我目前拥有的代码:

run_analysis:
    @echo "Get text files"
    txt_files=$(wildcard ./input/*.txt)
    @echo "Current text files are:"
    @echo $(txt_files)
    for txt_file in $(txt_files); do \
        @echo "Iteration" \
        @echo $(txt_file ) \
        python ./scripts/my_test_script.py $(txt_file ) ; \
    done

似乎通配符结果未存储在变量中。

我的输出如下所示:

Get text files
txt_files=./input/test_text_1.txt
Current text files are:

for txt_file in ; do \
    @echo "Iteration" \
    @echo  \
    python ./scripts/my_test_script.py  ; \
done

【问题讨论】:

    标签: makefile


    【解决方案1】:

    Makefile 配方中的每一行默认在单独的 shell 实例中执行。

    无论如何,将文件保存在变量中似乎没有任何用处。只需内联通配符。

    run_analysis:
        for txt_file in ./input/*.txt; do \
            python ./scripts/my_test_script.py "$$txt_file"; \
        done
    

    (请注意txt_file 是一个 shell 变量,而不是 Make 变量。)

    更好的是,更改您的 Python 脚本,使其接受输入文件列表。

    run_analysis:
        python ./scripts/my_test_script.py ./input/*.txt
    

    如果你想确切地看到它在做什么,也许可以在 Python 脚本中添加与 logging.debug() 的持续聊天。与硬编码的echo 不同,logging 可以在您确信自己的代码有效后轻松关闭。

    【讨论】:

    • 我尝试了您建议的答案,并且我的 python 脚本正在执行。但是,传递的参数是空的。由于输入参数为空,我对if passed_file.split(".")[-1] != "txt" 的检查评估为真。编辑:稍等一下,我的 makefile 中可能有错字……很快就会更新。
    • 谢谢。您的解决方案工作正常,但您能详细说明“$$txt_file”吗?我假设因为它是一个 shell 变量,我需要用另一个 $ 转义 $ 但为什么要加引号?
    • 我们基本上总是引用包含文件名的 shell 变量。 stackoverflow.com/questions/10067266/…
    猜你喜欢
    • 2019-07-20
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2018-01-19
    • 2021-08-01
    相关资源
    最近更新 更多