Simple process IO capture (Was: "shell-commands" and python!) - (0/1)

Paul Moore gustav at
Mon Sep 24 22:14:42 CEST 2001

On Sun, 23 Sep 2001 17:35:59 -0400 (EDT), in comp.lang.python you wrote:

>On Sun, 23 Sep 2001, Paul Moore wrote:
>> I did some looking. The attached is a fairly simple prototype of a module for
>> process handling. The simple examples
>Could you please send the attachment to python-list at so that us poor
>saps on the mailing list can see it too?

Sorry. I don't know why the attachment got stripped into a separate message, but
here it is again, as inline text. Apologies if it gets word-wrapped - I get the
feeling I'm not going to win either way, here :-)


process - run an OS command and handle standard input and output.

The module exports one main function, run(). This is a preliminary version of
the module, and as such run() has far too many options. But changing the
interface to a class-based one seems to defeat the object of the exercise,
which is to have an extremely simple (one-liner) interface.


    >>> import process
    >>> print"echo Hello, world")
    Hello, world
    >>> print"tr a-z A-Z", input = "Hello, world")
    >>> print"echo hello 1>&2") # No output, only stdout captured

    >>> print"echo hello 1>&2", capture_stderr = 1)
    >>> print'exit 1')

    >>> print process.retval()
    >>> print'exit 1', raise_exception=1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "", line 65, in run
        if rv: raise Error

class Error(Exception):

_retval = 0

    import win32pipe
    _popen2 = win32pipe.popen2
    _popen4 = win32pipe.popen4
except ImportError:
    import os
    _popen2 = os.popen2
    _popen4 = os.popen4

def retval():
    return _retval

def run(cmd, mode = 't', input = None,
        capture_stderr = None,
        raise_exception = None):

    if capture_stderr:
        (i, o) = _popen4(cmd, mode)
        (i, o) = _popen2(cmd, mode)

    if input:

    ret =
    rv = o.close()

    if raise_exception:
        if rv: raise Error
        global _retval
        _retval = rv

    return ret

More information about the Python-list mailing list