Assistance in understanding the sub-Process module

Tim Golden mail at timgolden.me.uk
Fri May 13 08:44:03 EDT 2011


On 13/05/2011 12:03, vijay swaminathan wrote:
> 1. The class definition as per the documentation is:
> /class /subprocess.Popen(/args/, /bufsize=0/, /executable=None/,
> /stdin=None/, /stdout=None/, /stderr=None/, /preexec_fn=None/,
> /close_fds=False/, /shell=False/, /cwd=None/, /env=None/,
> /universal_newlines=False/, /startupinfo=None/, /creationflags=0/)
> /args/ should be a string, or a sequence of program arguments.
> so I assume that args can be a string or a list with first item of the
> list being the program to execute.

That's more or less correct. A list is usually preferable as it leaves
the heavy-lifting of getting the quotes right to the underlying library.

> so on the python IDLE, I executed this command,
>  >>> subprocess.Popen('cmd.exe')
> <subprocess.Popen object at 0x00F5AA50> which opened up a command prompt.
> when I give this as a list, as below it throwed this error.
>  >>> subprocess.Popen(['cmd.exe', 'dir'])
> Traceback (most recent call last):
>    File "<pyshell#29>", line 1, in <module>
>      subprocess.Popen(['cmd.exe' 'dir'])
>    File "C:\Python26\lib\subprocess.py", line 623, in __init__
>      errread, errwrite)
>    File "C:\Python26\lib\subprocess.py", line 833, in _execute_child
>      startupinfo)
> WindowsError: [Error 2] The system cannot find the file specified

Well I would actually have expected it to open a command
prompt and do nothing else. If you do this in a (Windows)
command prompt:

   cmd /?

you can see that the way to run a command from with a command
shell is to use: cmd /c <whatever> (or /k which leaves the
console running afterwards). Note that you only even need to
launch cmd for internal commands which aren't executables in
their own right. ie you don't need to do cmd /c notepad since
notepad can run on its own.

So doing cmd <whatever> will just run cmd and, I think,
ignore the rest of the line. You actually want:

   import subprocess
   subprocess.Popen (["cmd", "/c", "dir"])

However, that is exactly what passing shell=True to Popen
does for you so...

   import subprocess
   subprocess.Popen ("dir", shell=True)
   # or subprocess.Popen (["dir"], shell=True)


TJG



More information about the Python-list mailing list