📜  如何在 python 代码示例中获取终端输出

📅  最后修改于: 2022-03-11 14:46:19.077000             🧑  作者: Mango

代码示例1
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2

>>> 

There is a bug in using of the subprocess.PIPE. For the huge output use this:

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()