Jiř*_*car 46
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
Run Code Online (Sandbox Code Playgroud)
使用subprocess.PIPE时出现错误.对于巨大的输出使用这个:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 18
请改用subprocess模块.
pipe = Popen("pwd", shell=True, stdout=PIPE).stdout
output = pipe.read()
Run Code Online (Sandbox Code Playgroud)
在Python 2.7中,您还可以使用该check_output()功能.
您可以使用POPEN中subprocess,他们建议.
with os,这不是推荐,如下所示:
import os
a = os.popen('pwd').readlines()
Run Code Online (Sandbox Code Playgroud)