Python 将在 bash 脚本中逐行读取的输出

Python output to be read inside bash script line by line

这里的基本思想是在每个 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 文件中读取任何内容。我在这里缺少什么?

您没有将输出文件提供给内部循环,尝试:

#!/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 中并在一个地方处理所有事情呢?

这将是 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

指定执行“技巧”in the manual:

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

[...] 如果未指定 command,重定向可能会影响当前的 shell 环境。