由于无法避免的原因,我正在使用Python 2.6。我已经在Idle命令行上运行了以下少量代码,但遇到了我不理解的错误。我该如何解决?
>>> import subprocess
>>> x = subprocess.call(["dir"])
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x = subprocess.call(["dir"])
File "C:\Python26\lib\subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python26\lib\subprocess.py", line 595, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 821, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>>
尝试设置shell=True
:
subprocess.call(["dir"], shell=True)
dir
是一个Shell程序,意味着没有可执行文件可以调用。因此dir
只能从外壳调用,因此是shell=True
。
注意,subprocess.call
仅执行命令而不提供输出。它只会返回它的退出状态(成功时通常为0)。
如果要获取输出,可以使用subprocess.check_output
:
>>> subprocess.check_output(['dir'], shell=True)
' Datentr\x84ger in Laufwerk C: ist … and more German output'
解释为什么它可以在Unix上运行:dir
实际上,这里有一个可执行文件,通常放在/bin/dir
,可以从PATH访问。在Windows中,dir
是PowerShell中命令解释器cmd.exe
或Get-ChildItem
cmdlet的功能(别名为dir
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句