link several Popen commands with pipes(用管道链接几个 Popen 命令)
问题描述
我知道如何使用 cmd = subprocess.Popen 然后 subprocess.communicate 来运行命令.大多数时候,我使用一个用 shlex.split 标记的字符串作为 Popen 的 'argv' 参数.以ls -l"为例:
导入子流程进口shlex打印 subprocess.Popen(shlex.split(r'ls -l'),stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE).communicate()[0]
但是,管道似乎不起作用...例如,以下示例返回注意:
导入子流程进口shlexprint subprocess.Popen(shlex.split(r'ls -l | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
你能告诉我我做错了什么吗?
谢谢
我想你想在这里实例化两个单独的 Popen 对象,一个用于ls",另一个用于sed".您需要将第一个 Popen 对象的 stdout
属性作为 stdin
参数传递给第二个 Popen 对象.
例子:
p1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)p2 = subprocess.Popen('sed ...', stdin=p1.stdout, stdout=subprocess.PIPE)打印 p2.communicate()
如果你有更多命令,你可以继续这样链接:
p3 = subprocess.Popen('prog', stdin=p2.stdout, ...)
有关如何使用子流程的更多信息,请参阅子流程文档.p>
I know how to run a command using cmd = subprocess.Popen and then subprocess.communicate. Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen. Example with "ls -l":
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
However, pipes seem not to work... For instance, the following example returns noting:
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
Can you tell me what I am doing wrong please?
Thx
I think you want to instantiate two separate Popen objects here, one for 'ls' and the other for 'sed'. You'll want to pass the first Popen object's stdout
attribute as the stdin
argument to the 2nd Popen object.
Example:
p1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)
p2 = subprocess.Popen('sed ...', stdin=p1.stdout, stdout=subprocess.PIPE)
print p2.communicate()
You can keep chaining this way if you have more commands:
p3 = subprocess.Popen('prog', stdin=p2.stdout, ...)
See the subprocess documentation for more info on how to work with subprocesses.
这篇关于用管道链接几个 Popen 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用管道链接几个 Popen 命令
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01