在Python中使用subprocess.call('dir',shell = True)时找不到指定的文件

问题描述 投票:16回答:3

在安装了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

然后我明白了

.

以上所有操作都在以管理员模式启动的终端中执行。

python shell python-2.7 path subprocess
3个回答
14
投票

我想你的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:开头的块,它将在环境中搜索所述变量并使用它来创建用于启动该过程的参数。


5
投票

在downvote之前,请注意我在发布此答案后编辑了问题。

我认为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')

这将运行命令,但它返回qazxsw poi,你无法存储它。


3
投票

如果除了我以外的任何人都没有立即在(3.4)0中看到这个:

在具有shell = True的Windows上,COMSPEC环境变量指定默认shell。您需要在Windows上指定shell = True的唯一时间是您希望执行的命令是否内置到shell中(例如dir或copy)。您不需要shell = True来运行批处理文件或基于控制台的可执行文件。

注意在使用shell = True之前,请阅读docs部分。


0
投票

使用Shell = True,它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.