Cannot find the file specified when using subprocess.call('dir', shell=True) in Python

后端 未结 4 755
北海茫月
北海茫月 2020-12-03 13:59

In a 64-bit system with 32 bit python 2.7 installed I am trying to do the following:

import subprocess
p = subprocess.call(\'dir\', shell=True)
print p
         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 14:41

    I think you may have a problem with your COMSPEC environment variable:

    >>> 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 "", line 1, in 
      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
    

    I discovered this potential issue by digging into subprocess.py and looking in the _execute_child function, as pointed-to by the traceback. There, you'll find a block starting with if shell: that will search the environment for said variable and use it to create the arguments used to launch the process.

提交回复
热议问题