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

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 "<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

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.

Leave a Comment