5

I am using Python 2.6 for reasons I cannot avoid. I have run the following tiny bit of code on the Idle command line and am getting an error I do not understand. How can I get around this?

>>> import subprocess
>>> x = subprocess.call(["dir"])

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x = subprocess.call(["dir"])
  File "C:\Python26\lib\subprocess.py", line 444, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python26\lib\subprocess.py", line 595, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 821, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> 
user442920
  • 857
  • 4
  • 21
  • 49

1 Answers1

20

Try setting shell=True:

subprocess.call(["dir"], shell=True)

dir is a shell command meaning there is no executable that you could call. So dir can only be called from a shell, hence the shell=True.

Note that subprocess.call will only execute the command without giving you its output. It will only return the exit status of it (usually 0 when it was successful).

If you want to get the output, you can use subprocess.check_output:

>>> subprocess.check_output(['dir'], shell=True)
' Datentr\x84ger in Laufwerk C: ist … and more German output'

To explain why it works on Unix: There, dir is actually an executable, usually placed at /bin/dir, and as such accessible from the PATH. In Windows, dir is a feature of the command interpreter cmd.exe or the Get-ChildItem cmdlet in PowerShell (aliased to dir).

miken32
  • 42,008
  • 16
  • 111
  • 154
poke
  • 369,085
  • 72
  • 557
  • 602