您似乎想要存储来自subprocess.Popen() 调用的输出。
如需更多信息,请参阅Subprocess - Popen.communicate(input=None)。
>>> import subprocess
>>> test = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
fizzbuzz.py
foo.py
[..]
但是,Windows shell (cmd.exe) 没有 ls 命令,但还有另外两种选择:
使用os.listdir() - 这应该是首选方法,因为它更容易使用:
>>> import os
>>> os.listdir("C:\Python27")
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe
', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']
使用 Powershell - 默认安装在较新版本的 Windows (>= Windows 7) 上:
>>> import subprocess
>>> test = subprocess.Popen(['powershell', '/C', 'ls'], stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
Directory: C:\Python27
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 14.05.2013 16:00 DLLs
d---- 14.05.2013 16:01 Doc
[..]
使用 cmd.exe 的 Shell 命令是这样的:
test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)
欲了解更多信息,请参阅:
The ever useful and neat subprocess module - Launch commands in a terminal emulator - Windows
注意事项: