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.


Before downvote, note that the question was edited after i posted this answer.

I think os.listdir is more suitable for your case:

>>> 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']

If you want to run it in the command line itself, and just feeling like to call it, you can use os.sytem:

os.system('dir')

This will run the commmand, but it returns 0 and you can't store it.


In case anyone else besides me doesn't see this in the (3.4) docs right away:

On Windows with shell=True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.

Note Read the Security Considerations section before using shell=True.