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
>>> 
                Try setting shell=True:
subprocess.call(["dir"], shell=True)
dir is a shell program 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With