链接几个Popen命令与管道 [英] link several Popen commands with pipes
问题描述
我知道如何使用cmd = subprocess.Popen和subprocess.communicate运行命令。
大多数时候,我使用一个字符串与shlex.split作为'argv'参数为Popen。
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]
但是,管道似乎不工作...例如,以下示例返回注意:
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l | seds / a / b / g ),stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE).communicate()[0]
b $ b你能告诉我我在做什么错了吗?
Thx
方案我想你想在这里实例化两个单独的Popen对象,一个用于'ls',另一个用于'sed'。你需要将第一个Popen对象的
stdout
属性作为stdin
参数传递给第二个Popen对象。 p>
示例:
p1 = subprocess.Popen('ls ... ',stdout = subprocess.PIPE)
p2.communicate()
p2 = subprocess.Popen('sed ...',stdin = p1.stdout,stdout = subprocess.PIPE) b如果您有更多命令,可以保持此链接:
p3 = subprocess.Popen('prog',stdin = p2.stdout,...)
有关如何使用子流程的更多信息,请参见子流程文档 。
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 thestdin
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命令与管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!