Python 子进程:使用 subprocess.run 链接命令 [英] Python subprocess: chaining commands with subprocess.run
问题描述
我正在 Python 中试验 subprocess.run3.5.将两个命令链接在一起,我认为以下应该有效:
I'm experimenting with subprocess.run in Python 3.5. To chain two commands together, I would have thought that the following should work:
import subprocess
ps1 = subprocess.run(['ls'], universal_newlines=True, stdout=subprocess.PIPE)
ps2 = subprocess.run(['cowsay'], stdin=ps1.stdout)
然而,这失败了:
AttributeError: 'str' object has no attribute 'fileno'
ps2
需要一个类似文件的对象,但 ps1
的输出是一个简单的字符串.
ps2
was expecting a file-like object, but the output of ps1
is a simple string.
有没有办法将命令与 subprocess.run
链接在一起?
Is there a way to chain commands together with subprocess.run
?
推荐答案
subprocess.run()
不能用于实现 ls |cowsay
没有外壳,因为它不允许同时运行单个命令:每个 subprocess.run()
调用等待进程完成,这就是它返回 CompletedProcess 的原因
对象(注意那里的已完成"一词).ps1.stdout
在您的代码中是一个字符串,这就是为什么您必须将其作为 input
而不是期望文件的 stdin
参数传递的原因/管道(有效 .fileno()
).
subprocess.run()
can't be used to implement ls | cowsay
without the shell because it doesn't allow to run the individual commands concurrently: each subprocess.run()
call waits for the process to finish that is why it returns CompletedProcess
object (notice the word "completed" there). ps1.stdout
in your code is a string that is why you have to pass it as input
and not the stdin
parameter that expects a file/pipe (valid .fileno()
).
要么使用shell:
subprocess.run('ls | cowsay', shell=True)
或者使用subprocess.Popen
,并发运行子进程:
Or use subprocess.Popen
, to run the child processes concurrently:
from subprocess import Popen, PIPE
cowsay = Popen('cowsay', stdin=PIPE)
ls = Popen('ls', stdout=cowsay.stdin)
cowsay.communicate()
ls.wait()
请参阅如何使用 subprocess.Popen 通过管道连接多个进程?
这篇关于Python 子进程:使用 subprocess.run 链接命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!