在运行os.system
调用后,我希望将stdout
存储到变量中。
让我们以这行代码为例:
batcmd="dir"
result = os.system(batcmd)
result
将包含错误代码(在Windows下为stderr
0
,在某些Linux系统中为1
)。
如何在不使用执行命令重定向的情况下获取上述命令的stdout
?
在运行os.system
调用后,我希望将stdout
存储到变量中。
让我们以这行代码为例:
batcmd="dir"
result = os.system(batcmd)
result
将包含错误代码(在Windows下为stderr
0
,在某些Linux系统中为1
)。
如何在不使用执行命令重定向的情况下获取上述命令的stdout
?
如果您只需要stdout
输出,那么可以看一下subprocess.check_output()
:
import subprocess
batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)
因为您正在使用os.system()
,所以您需要设置shell=True
才能获得相同的行为。但是,您确实需要注意有关将不受信任的参数传递给 shell 的安全问题。stderr
,只需在调用中添加stderr=subprocess.STDOUT
即可:result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)
将错误输出重定向到默认输出流。text=True
以使用平台默认编码对返回的字节值进行解码;如果该编解码器不适用于接收到的数据,则改为使用encoding="..."
。result = subprocess.check_output(["cmd.exe", batcmd])
。 - Eduard Florinescushell=True
;这在subprocess
文档中提到过,但我在这里明确指出。 - Martijn Pieterscwd
参数设置为subprocess.check_output()
。 - Martijn Pieters这些答案对我没用。我不得不使用以下方法:
import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out
或者作为一个函数(在Python 2.6.7上需要使用shell=True,而check_output直到2.7版本才被添加,因此在这里无法使用):
def system_call(command):
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read()
import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)
由于在处理较大的任务时subprocess会出现内存错误,因此我不得不使用os.system。关于这个问题的参考资料在这里。为了获得os.system命令的输出,我使用了以下解决方法:
import os
batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
fp = open('output.txt', "r")
output = fp.read()
fp.close()
os.remove('output.txt')
print(output)
os.system()
同样在底层使用fork()
/clone()
,那么这有什么优势呢? - Charles Duffyshlex.quote()
(或其Python 2.x等效物pipes.quote()
)对所有文件名进行转义,否则,如果有人在您的上传文件夹中放置一个名为$(rm -rf ~)'$(rm -rf ~)'.mpg
的文件,那么您可能会度过非常糟糕的一天。 - Charles Duffy我希望为Windows解决方案提供更多说明。使用Python 2.7.5的IDLE,当我运行文件Expts.py时,会出现以下代码:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
在Python Shell中,我只会得到与“cmd.exe”相对应的输出;“dir”部分被忽略了。然而,当我添加一个开关,比如/K或/C...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
然后在Python Shell中,我得到了我期望的一切,包括目录列表。太棒了!
现在,如果我在DOS Python命令窗口中尝试任何相同的操作,没有使用开关或使用/K开关,它似乎会使窗口挂起,因为它正在运行一个子进程cmd.exe并等待进一步的输入-键入'exit'然后按[enter]以释放。但是使用/K开关,它可以完美地工作,并返回到python提示符。好吧。
更进一步......我认为这很酷......当我在Expts.py中执行以下操作时:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
commands
也可以使用。
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
subprocess
模块代替os.system
,因为os.system
无法访问进程的输入或输出。 - Martijn Pieterssubprocess
模块比你能做到的更好地封装了 Windows 和 POSIX 系统之间的差异。为什么要重新发明轮子呢? - Martijn Pieterssubprocess.check_output()
函数,这可能已经足够满足您的需求,但除此之外,这两个目标是几乎等价的。 - Martijn Pieters