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

发布于 2021-01-29 18:23:18

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

然后我得到

.

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

关注者
0
被浏览
211
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看