【问题标题】:Running Python With STDIN From Bash从 Bash 使用 STDIN 运行 Python
【发布时间】:2010-03-01 09:06:35
【问题描述】:

我有一个 bash 代码 (Mybash1.sh) 我需要传递的结果 到另一个包含 Python 的 bash 代码 (Mybash2.sh)

这里是代码。 Mybash1.sh

#! /bin/bash
# Mybash1.sh
cut -f1,3 input_file.txt | sort | ./Mybash2.sh 

Mybash2.sh 是这样的:

#! /bin/bash
#Mybash2.sh
python mycode.py foo.txt <("$@") > output.txt
# do something for output.txt

我遇到的问题是Mybash2.sh 中的“output.txt”不包含任何结果。 在Mybash2.sh中是否有正确的方式执行Python?

请注意,mycode.py 如果我在中间临时运行它就可以工作 来自Mybash1.sh 的文件。但我想避免使用它,因为我会打电话给Mybash2.shMybash1.sh 中的许多情况下。

mycode.py 的片段如下所示:

if __name__ == "__main__":
    import sys, os, fileinput
    progName = os.path.basename(sys.argv[0])
    if len(sys.argv) != 3:
        sys.exit('Usage: ' + progName + ' file1 file2')
    file1 = fileinput.input(sys.argv[1])
    file2 = fileinput.input(sys.argv[2])

    # do something for file1 and file2

    file1.close()
    file2.close()

【问题讨论】:

    标签: python linux bash unix stdin


    【解决方案1】:

    在 python 中,你想要file2 = sys.stdin

    然后:

    #! /bin/bash
    #Mybash2.sh
    python mycode.py foo.txt > output.txt
    

    编辑:我刚刚看过 fileinput 文档,似乎如果您向 fileinput.input() 提供“-”,它将读取标准输入,因此无需对 Python 进行任何更改,这应该可以:

    #! /bin/bash
    #Mybash2.sh
    python mycode.py foo.txt - > output.txt
    

    【讨论】:

      【解决方案2】:

      在您的 myscript1.sh 中,您将管道传递给 myscript2.sh,因此,它是 myscript2.sh 的某种标准输入。您应该从 myscript2.sh 中读取该 STDIN,而不是接受输入参数。例如 myscript2.sh

      #!/bin/bash
      while read myinput
      do
       echo "myinput is $myinput"
       # assuming you are passing each input line from the cut command into Python
       python mycode.py foo.txt $myinput > output.txt
      done
      

      最后,为什么所有这些依赖项?你不能用 Python 或 shell 做所有事情吗??

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 2013-03-14
        • 1970-01-01
        • 2015-12-06
        • 2018-03-14
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多