Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess not working in Python

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
>>> 
like image 777
user442920 Avatar asked Oct 08 '13 20:10

user442920


1 Answers

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).

like image 67
poke Avatar answered Oct 06 '22 20:10

poke