使用python运行其他程序

2024-05-04 05:40:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个命令,在命令行上工作得很好。它有很多参数,比如cmd --thing foo --stuff bar -a b input output

我想从python运行这个程序并阻塞它,等待它完成。当脚本将内容打印到stdoutstderr时,我希望它立即显示给用户。

哪个模块适合这个?

我试过:


import commands
output = commands.getoutput("cmd --thing foo --stuff bar -a b input output")
print output

这很好,只是stdout直到结束才返回。


import os
os.system("cmd --thing foo --stuff bar -a b input output")

这将在实际完成命令时打印所有输出。


import subprocess
subprocess.call(["cmd", "--thing foo", "--stuff bar", "-a b", "input", "output"])

这不能以某种方式正确地传递参数(我还没有找到确切的问题,但是cmd拒绝了我的输入)。如果我将echo作为第一个参数,当我将命令直接粘贴到终端时,它会打印出工作正常的命令。


import subprocess
subprocess.call("cmd --thing foo --stuff bar -a b input output")

与上述完全相同。


Tags: import命令cmdinputoutput参数fooos
3条回答

commands.getstatusoutput()不起作用吗?它会立刻恢复你的状态。

如果您不需要处理代码中的输出,只需要在它发生时向用户显示它(从您的Q中看不清楚,从您自己的答案来看似乎是这样),最简单的方法是:

rc = subprocess.call(
    ["cmd", "--thing", "foo", "--stuff", "bar", 
     "-a", "b", "input", "output"])
print "Return code was", rc

也就是说,不要使用任何管道——让stdout和stderr显示在终端上。这应该可以避免缓冲的任何问题。一旦你在图片中放置了管道,缓冲通常是一个问题,如果你想在它发生时显示输出(我很惊讶你的自我回答没有这个问题;-)。

对于显示捕获,顺便说一句,我总是建议pexpect(和wexpect在Windows上)精确地解决缓冲问题。

你必须分别引用每个字段,即从它们的参数中分割选项。

import subprocess
output = subprocess.call(["cmd", "--thing", "foo", "--stuff", "bar", "-a", "b", "input", "output"])

否则你就可以像这样有效地运行cmd

$ cmd --thing\ foo --stuff\ bar -a\ b input output

要将输出放入管道中,需要对其进行稍微不同的调用

import subprocess
output = subprocess.Popen(["cmd", "--thing", "foo", "--stuff", "bar", "-a", "b", "input", "output"],stdout=subprocess.PIPE)
output.stdout   #  <open file '<fdopen>', mode 'rb'>

相关问题 更多 >