Subprocess not working in Python

I am using Python 2.6 for reasons that I cannot avoid. I ran the next small bit of code on the Idle command line and get an error that I don't 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
>>> 
+4
source share
1 answer

Try to install shell=True:

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

diris a shell program, meaning that the executable cannot be called. Therefore, dirit can only be called from the shell, therefore shell=True.

Please note that subprocess.callonly the command will be executed without giving you its output. It will return the exit status from it (usually 0 when it was successful).

, subprocess.check_output:

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

, Unix: dir , /bin/dir PATH. Windows dir - cmd.exe Get-ChildItem PowerShell ( dir).

+11

All Articles