Ale*_*lds 8 python stdin subprocess stdout io-redirection
我的Python脚本中有一个标志,指定我是否设置和使用外部进程.此过程是一个调用的命令my_command,它从标准输入中获取数据.如果我在命令行上运行它,它将是这样的:
$ my_command < data > result
Run Code Online (Sandbox Code Playgroud)
我想使用Python脚本data通过修改标准输入并将其输入来生成行my_command.
我正在做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
但是,my_command表现得好像它没有收到任何数据并退出并显示错误状态.我究竟做错了什么?
编辑
假设我的Python脚本被调用了my_Python_script.假设我通常会传递my_command一个data通过标准输入调用的文件:
$ my_command < data > result
Run Code Online (Sandbox Code Playgroud)
但现在我把它传给了my_Python_script:
$ my_Python_script < data > some_other_result
Run Code Online (Sandbox Code Playgroud)
我想my_Python_script有条件地设置一个运行my_command在内容上的子进程data(my_Python_script在传递之前进行修改my_command).这更有意义吗?
如果我bash用作脚本语言,我会有条件地决定运行两个函数之一.一个人可以管道数据my_command.另一个不会.可以用Python完成吗?
写入stdin后,需要关闭它:
process.stdin.write(modified_line)
process.stdin.close()
Run Code Online (Sandbox Code Playgroud)
我没注意到它process.stdin.write()是在for循环中执行的.在这种情况下,您应该移动process.stdin.close()到循环外部.
此外,雷蒙德提到我们也应该打电话process.wait().所以更新的代码应该是:
for ...
process.stdin.write(modified_line)
process.stdin.close()
process.wait()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3492 次 |
| 最近记录: |