A problem with subprocess

Tim Golden mail at timgolden.me.uk
Sat Mar 21 07:58:13 CET 2009


Colin J. Williams wrote:
> Below is a test script:
> 
> # tSubProcess.py
> 
> import subprocess
> import sys
> try:
>   v= subprocess.Popen('ftype py=C:\Python25\Python.exe')
> except WindowsError:
>   print(sys.exc_info())

I'm assuming that you've previously done something like this:

  assoc .py=py

and are now trying to do this:

  ftype py=c:\python25\python.exe

You've got a few issues to resolve there. If you're using a
string containing a backslash (basically, any Windows path)
you need to tell Python to treat the backslash as a backslash
and not as an escape character. Simplest way to do this is
to prefix the string with r for raw:

  r"ftype py=c:\python25\python.exe"

In this case it wouldn't matter too much because \p isn't
a recognised escape sequence. But as soon as you hit, say,
"c:\files" you'll be in trouble because \f is the escape
sequence for ASCII 12.


OK. The next thing is that ftype is not actually an .exe
in its own right: it's provided by the command shell
(cmd.exe or whatever). That means you have to ask the
subprocess module to call the shell on your behalf:

  subprocess.Popen (r"...", shell=True)

Finally, for simple do-it-and-finish subprocess calls like
yours, it's generally advantageous to use the convenience
function .call, and pass the params as a list of params
which avoid other issues to do with embedded spaces.
(Usually: there is an outstanding bug there). So...


import subprocess
subprocess.call (["ftype", r"py=c:\python25\python.exe"], shell=True)


TJG



More information about the Python-list mailing list