Simple process IO capture (Was: "shell-commands" and python!) - process.py (0/1)
Paul Moore
gustav at morpheus.demon.co.uk
Mon Sep 24 16:14:42 EDT 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 python.org 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 :-)
Paul.
"""
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.
Examples:
>>> import process
>>> print process.run("echo Hello, world")
Hello, world
>>> print process.run("tr a-z A-Z", input = "Hello, world")
HELLO, WORLD
>>> print process.run("echo hello 1>&2") # No output, only stdout captured
>>> print process.run("echo hello 1>&2", capture_stderr = 1)
hello
>>> print process.run('exit 1')
>>> print process.retval()
1
>>> print process.run('exit 1', raise_exception=1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "process.py", line 65, in run
if rv: raise Error
process.Error
"""
class Error(Exception):
pass
_retval = 0
try:
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)
else:
(i, o) = _popen2(cmd, mode)
if input:
i.write(input)
i.close()
ret = o.read()
rv = o.close()
if raise_exception:
if rv: raise Error
else:
global _retval
_retval = rv
return ret
More information about the Python-list
mailing list