Ame*_*ina 9 python shell subprocess pipe
我在使用Python调用shell命令时读取了我在StackOverflow上找到的每个线程subprocess,但我找不到适用于我的情况的答案:
我想从Python中执行以下操作:
运行shell命令command_1.收集变量中的输出result_1
Shell管道 result_1进入command_2并收集输出result_2.换句话说,command_1 | command_2 使用我在之前的步骤中运行时获得的结果运行command_1
将相同的管道result_1输入第三个命令command_3并收集结果result_3.
到目前为止,我尝试过:
p = subprocess.Popen(command_1, stdout=subprocess.PIPE, shell=True)
result_1 = p.stdout.read();
p = subprocess.Popen("echo " + result_1 + ' | ' +
command_2, stdout=subprocess.PIPE, shell=True)
result_2 = p.stdout.read();
Run Code Online (Sandbox Code Playgroud)
原因似乎是"echo " + result_1 不能模拟获得管道命令输出的过程.
这是否可以使用子进程?如果是这样,怎么样?
你可以做:
pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE)
pipe.stdin.write(result_1)
pipe.communicate()
Run Code Online (Sandbox Code Playgroud)
而不是与管道的线.
| 归档时间: |
|
| 查看次数: |
1671 次 |
| 最近记录: |