用管道链接多个 Popen 命令
我知道如何使用 cmd = subprocess.Popen 然后使用 subprocess.communicate 运行命令。 大多数时候,我使用 shlex.split 标记的字符串作为 Popen 的“argv”参数。 使用“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 | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
您能告诉我我做错了什么吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您想在这里实例化两个单独的 Popen 对象,一个用于“ls”,另一个用于“sed”。您需要将第一个 Popen 对象的
stdout
属性作为stdin
参数传递给第二个 Popen 对象。示例:
如果您有更多命令,您可以继续以这种方式链接:
请参阅子流程文档了解有关如何使用子流程的更多信息。
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:
You can keep chaining this way if you have more commands:
See the subprocess documentation for more info on how to work with subprocesses.
我做了一个小功能来帮助管道,希望它有帮助。它将根据需要链接 Popens。
I've made a little function to help with the piping, hope it helps. It will chain Popens as needed.
shlex
仅根据shell规则分割空格,但不处理管道。然而,它应该这样工作:
根据
help(subprocess)
'sHTH
shlex
only splits up spaces according to the shell rules, but does not deal with pipes.It should, however, work this way:
according to
help(subprocess)
'sHTH
感谢@hernvnc、@glglgl 和@Jacques Gaudin 的回答。我修复了@hernvnc 的代码。他的版本在某些情况下会导致挂起。
Thank @hernvnc, @glglgl, and @Jacques Gaudin for the answers. I fixed the code from @hernvnc. His version will cause hanging in some scenarios.