【发布时间】:2013-02-24 16:43:27
【问题描述】:
我的 Python 脚本中有一个标志,它指定我是否设置和使用外部进程。这个过程是一个名为my_command 的命令,它从标准输入中获取数据。如果我要在命令行上运行它,它会是这样的:
$ my_command < data > result
我想使用 Python 脚本通过修改标准输入并将其提供给 my_command 来生成 data 行。
我正在做这样的事情:
import getopt, sys, os, stat, subprocess
# for argument's sake, let's say this is set to True for now
# in real life, I use getopt.getopt() to decide whether this is True or False
useProcess = True
if useProcess:
process = subprocess.Popen(['my_command'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in sys.stdin:
# parse line from standard input and modify it
# we store the result in a variable called modified_line
modified_line = line + "foo"
# if we want to feed modified_line to my_command, do the following:
if useProcess:
process.stdin.write(modified_line)
# otherwise, we just print the modified line
else:
print modified_line
但是,my_command 的行为就好像它没有收到任何数据并以错误状态退出。我做错了什么?
编辑
假设我的 Python 脚本名为 my_Python_script。假设我通常会通过标准输入传递 my_command 一个名为 data 的文件:
$ my_command < data > result
但现在我将其传递给my_Python_script:
$ my_Python_script < data > some_other_result
我希望my_Python_script 有条件地设置一个子进程,该子进程在data 的内容上运行my_command(在传递给my_command 之前由my_Python_script 修改)。这更有意义吗?
如果我使用bash 作为脚本语言,我会有条件地决定运行两个函数之一。一种是将数据行传输到my_command。另一个不会。这可以用 Python 完成吗?
【问题讨论】:
-
my_command是什么文件?它是一个shell脚本吗? Python脚本?您可能想尝试类似 ['/bin/bash', 'my_command'] 或类似的 Python 脚本。 -
您可以将
my_python_script写成 Unix 过滤器。然后python脚本对my_command一无所知,只是从stdin读取,以某种方式修改它,然后打印到stdout:`some_other_result -
如果是
stdout=PIPE,那么你应该从中读取,否则如果它产生足够的输出,进程可能会阻塞。 -
主进程和子进程之间双向通信的简单示例可以在这里找到:stackoverflow.com/a/52841475/1349673
标签: python subprocess stdout stdin io-redirection