Skip to main content
 首页 » 编程设计

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

2024年10月01日7lori

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

请您参考如下方法:

这将是 process substitution 的好地方和执行:

#!/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]]

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