【问题标题】:Python output to be read inside bash script line by line在 bash 脚本中逐行读取 Python 输出
【发布时间】:2017-12-22 12:50:23
【问题描述】:

这里的基本思想是在每次 curl 调用中调用 asd 目录中的 1 个文件和 output.txt 文件中的 1 行:

#!/bin/bash
python MJD.py -> output.txt
FILES=/home/user/asd/*
for f in $FILES
do
filename="$output.txt"
while read -r line
do
curl -F ID='zero' -F dir="@$f" -F TIME="$line" -F outputFormat=json "http://blabla"
done
done

此代码实际上调用了 python 脚本并将输出保存在 output.txt 文件中。输出文件每行只有 1 个数字,用于几行。现在我想要做的是,从第一行开始,为 -F TIME=" 文本文件中的一个值"。

我不知道我的代码的哪一部分导致了问题。当我调用此脚本时,从 dir 调用文件的部分有效,但每次 TIME=0 出现在屏幕上时,似乎没有从 output.txt 文件中读取任何内容。我在这里缺少什么?

【问题讨论】:

    标签: python bash loops lines


    【解决方案1】:

    这是process substitutionexec 的好地方:

    #!/bin/bash
    
    exec 4< <( python MJD.py - )
    # now, the output from the python script can be read from channel 4
    
    for file in /home/user/asd/*; do
        IFS= read -u4 -r time              # get the next line from MJD.py
        curl -F ID='zero' -F dir="@$file" -F TIME="$time" -F outputFormat=json "http://blabla"
    done
    

    该 exec “技巧”被指定为 in the manual:

    exec [-cl] [-a name] [command [arguments]]

    [...] 如果没有指定 command,则可能会使用重定向来影响当前的 shell 环境。

    【讨论】:

    • 谢谢!现在一切都像一个魅力。我理解这个想法,但我应该查看该手册并了解更多相关信息。再次,非常感谢!
    【解决方案2】:

    你没有给你的内部循环提供输出文件,试试:

    #!/bin/bash
    python MJD.py > output.txt
    FILES=/home/user/asd/*
    for f in $FILES
    do
    filename="output.txt"
    while read -r line
    do
    curl -F ID='zero' -F dir="@$f" -F TIME="$line" -F outputFormat=json "http://blabla"
    done < "$filename"
    done
    

    虽然,既然您已经在使用 Python,为什么不直接用 Python 编写所有逻辑并在一个地方处理所有事情呢?

    【讨论】:

    • 我已经了解了这里的情况并纠正了它,现在它可以工作了。但是,它适用于所有值。 dir路径中有2个文件,txt文件中有2个值。当此代码工作时,它会逐个应用每个人,创建 4 个结果。我需要的只是 2 个结果,来自 dir 的 1 个条目和来自 txt 的 1 行,从第一个开始直到它们第一次完成,所以只有 2 个结果和一次它完成了循环停止。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 2017-12-20
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2021-07-13
    • 2011-12-18
    相关资源
    最近更新 更多