[英]Cannot find the file specified when using subprocess.call('dir', shell=True) in Python
在安装了32位python 2.7的64位系统中,我尝试执行以下操作:
import subprocess
p = subprocess.call('dir', shell=True)
print p
但这给了我:
Traceback (most recent call last):
File "test.py", line 2, in <module>
p = subprocess.call('dir', shell=True)
File "C:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 709, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 957, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
如果我在航站楼里...
dir
...它当然会打印当前的文件夹内容。
我试图将shell参数更改为shell = False。
编辑:实际上我不能使用subprocess.call()
在路径上调用任何可执行文件。 语句p = subprocess.call('dir', shell=True)
在另一台机器上工作正常,我认为这是相关的。
如果我做
subprocess.call('PATH', shell=True)
然后我得到
Traceback (most recent call last):
File "test.py", line 4, in <module>
subprocess.call('PATH', shell=True)
File "C:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 709, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 957, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
如果我做:
import os
print os.curdir
然后我得到
.
以上所有操作均在以管理员模式启动的终端中执行。
我认为您的COMSPEC
环境变量可能有问题:
>>> import os
>>> os.environ['COMSPEC']
'C:\\Windows\\system32\\cmd.exe'
>>> import subprocess
>>> subprocess.call('dir', shell=True)
(normal output here)
>>> os.environ['COMSPEC'] = 'C:\\nonexistent.exe'
>>> subprocess.call('dir', shell=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python27\lib\subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "c:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "c:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
我通过钻研发现了这个潜在的问题subprocess.py
并期待在_execute_child
通过追踪功能,指向的。 在那里,您将找到一个以if shell:
开头的块,它将在环境中搜索所述变量,并使用其创建用于启动进程的参数。
在降级投票之前,请注意,在我发布此答案后,问题已被编辑。
我认为os.listdir
更适合您的情况:
>>> import os
>>> os.listdir()
['1.txt', '2.txt', '3.txt', 'DLLs', 'Doc', 'e.txt', 'include', 'Lib', 'libs', 'LICENSE.txt', 'm.txt', 'msvcr100.dll', 'NEWS.txt', 'py.exe', 'python.exe', 'python33.dll', 'pythonw.exe', 'pyw.exe', 'README.txt', 'Scripts', 't.txt', 'tcl', 'Tools']
如果您想在命令行本身中运行它,并且只是想调用它,可以使用os.sytem
:
os.system('dir')
这将运行命令,但返回0
,您将无法存储它。
使用Shell = True,它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.