代码之家  ›  专栏  ›  技术社区  ›  NapolyoN

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

  •  2
  • NapolyoN  · 技术社区  · 9 年前

    这里的基本思想是从asd目录中调用一个文件,从输出中调用一行。每个curl调用中的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
    done
    

    这段代码实际上调用了python脚本,并将输出保存在输出中。txt文件。对于几行,输出文件每行只有一个数字。现在我想做的是,从第一行开始,获取-F TIME=“文本文件中的一个值”。

    我不知道代码的哪一部分导致了这个问题。当我调用这个脚本时,从dir调用文件的部分可以工作,但每次屏幕上出现time=0时,输出中似乎什么都没有读取。txt文件..我缺少什么?

    2 回复  |  直到 9 年前
        1
  •  2
  •   Community Mohan Dere    6 年前

    这将是一个好地方 process substitution exec :

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

    […]如果否 命令

        2
  •  0
  •   zwer    9 年前

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

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