from subprocess import * test = subprocess.Popen('ls') print test
当我尝试运行这个简单的代码,我得到一个错误窗口说:
WindowsError: [Error 2] The system cannot find the file specified
我不知道为什么我不能得到这个简单的代码工作,这是令人沮丧的,任何帮助将不胜感激!
它看起来像你想要存储subprocess.Popen()
调用的输出。
欲了解更多信息,请参阅子进程 – 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)
有关更多信息,请参阅
永远有用和整洁的子进程模块 – 在终端模拟器启动命令 – Windows
笔记:
shell=True
因为这是一个安全风险。 shell=True
? from module import *
。 看看为什么你不应该使用语言构造 subprocess.Popen()
时候,它甚至不能用于这个目的。 同意,同意; Windows没有ls
命令。 如果你想在Windows上使用ls
这样的目录列表,可以使用dir /B
作为单列,或者使用dir /w /B
作为多列。 或者只是使用os.listdir
。 如果使用dir
,则必须使用subprocess.Popen(['dir', '/b'], shell=True)
启动子subprocess.Popen(['dir', '/b'], shell=True)
。 如果要存储输出,请使用subprocess.Popen(['dir', '/b'], shell=True, stdout=subprocess.PIPE)
。 而且,我使用shell=True
的原因是,由于dir
是内部DOS命令,所以必须使用shell来调用它。 / b去掉标题,而/ w强制多列输出。