subprocess vs. proctools

Donn Cave donn at drizzle.com
Tue Dec 14 11:35:42 EST 2004


Keith Dart <kdart at kdart.com> wrote:
|>> Oh, I forgot to mention that it also has a more user- and 
|>> programmer-friendly ExitStatus object that processess can return. This 
|>> is directly testable in Python:
|>>
|>> proc = proctools.spawn("somecommand")
|>> exitstatus = proc.wait()
|>>
|>> if exitstatus:
|>> 	print "good result (errorlevel of zero)"
|>> else:
|>>      print exitstatus # prints message with exit value

This is indeed how the shell works, though the actual failure value
is rarely of any interest.  It's also in a more general sense how
C works - whether errors turn out to be "true" or "false", in either
case you test for that status (or you don't.)

Python doesn't work that way, there is normally no such thing as
an error return.  An idiomatic Python interface would be

    try:
        proc = proctools.spawn(command)
        proc.wait()
        print 'good result'
    except proctools.error, ev:
        print >> sys.stderr, '%s: %s' % (proc.name, ev.text)

[... list of features ...]

| You always invoke the spawn* functions with a string. This is parsed by 
| a shell-like parser (the shparser module that comes with it), but no 
| /bin/sh is invoked. The parser can handle single and double quotes, and 
| backslash escapes.

It was sounding good up to here.  A lot depends on the quality of
the parser, but it's so easy to support a list of arguments that
gets passed unmodified to execve(), and such an obvious win in the
common case where the command parameters are already separate values,
that an interface where you "always" have to encode them in a string
to be submitted to your parser seems to be ignoring the progress that
os.spawnv and popen2.Popen3 made on this.  Of course you don't need
to repeat their blunders either and accept either string or list of
strings in the same parameter, which makes for kind of a shabby API,
but maybe a keyword parameter or a separate function would make sense.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list