nrvr.process.commandcapture
index
/usr/lib/python2.7/site-packages/nrvr/process/commandcapture.py

nrvr.process.commandcapture - Subprocesses wrapped for automation
 
The main class provided by this module is CommandCapture.
 
It should work in Linux and Windows.
 
On the downside, nothing has been coded yet in this module to allow input
into a running subprocess.
 
Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
 
Public repository - https://github.com/srguiwiz/nrvr-commander
 
Copyright (c) Nirvana Research 2006-2015.
Simplified BSD License

 
Modules
       
os
pty
re
subprocess
sys
threading
time

 
Classes
       
__builtin__.object
CommandCapture
exceptions.Exception(exceptions.BaseException)
CommandCaptureException
threading.Thread(threading._Verbose)
StreamCollector

 
class CommandCapture(__builtin__.object)
    A subprocess wrapped for automation.
 
This class uses subprocess.Popen.
It further wraps for better use in automation.
 
This class captures returncode, stdout and stderr.
 
This class copies to stdio, unless constructed with copyToStdio=False.
 
If module pty is available (e.g. in Python 2.6 on Linux, but not on Windows)
and output is copied to stdio, and unless constructed with forgoPty=True,
then uses pty.openpty() in order to see output right away.  Else uses pipes.
Reason has been, more commands are flushing their stdout more often when
they are thinking they are talking to a terminal, e.g. a pseudo-terminal,
rather than buffering their output when they are thinking they are talking
to a pipe.
 
What is nice about this class, it keeps separate stdout and stderr while
providing streaming output of both.
Having separate stderr does make a difference not only for easily separately
processing what the subprocess is writing to stderr, but also by maintaining
the ability to show stderr in a different color, e.g. in red if using
http://sourceforge.net/projects/hilite/.
 
True defaults exceptionIfNotZero=True and exceptionIfAnyStderr=True should
make for less hidden surprises when a subprocess encounters a problem,
because exceptions by default would propagate up in a system of scripts,
rather than being absorbed silently.
Obviously, these parameters can be set False if needed.
 
It should work in Linux and Windows.
 
On the downside, nothing has been coded in this class to allow input
into a running subprocess.
 
  Methods defined here:
__init__(self, args, copyToStdio=True, forgoPty=False, exceptionIfNotZero=True, exceptionIfAnyStderr=True)
Create new CommandCapture instance.
 
Will wait until completed.
 
Example use::
 
    example = CommandCapture(["hostname"])
    print "returncode=" + str(example.returncode)
    print "stdout=" + example.stdout
    print >> sys.stderr, "stderr=" + example.stderr
 
args
    are passed on to subprocess.Popen().
    
    If given a string instead of a list then fixed by args=args.split() making a list.
    That may only work as expected for some commands on some platforms.
    It should work for a command without arguments.
    
    Hence if you don't want a string split, pass it in wrapped as sole item of a list.
raiseExceptionIfThereIsAReason(self)
Raise a CommandCaptureException if there is a reason.
 
Available to provide standardized exception content in case calling code
with exceptionIfAnyStderr=False after looking at .stderr decides
in some circumstances only to raise an exception.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
returncode
Int returncode of subprocess.
stderr
Collected stderr string of subprocess.
stdout
Collected stdout string of subprocess.

 
class CommandCaptureException(exceptions.Exception)
    
Method resolution order:
CommandCaptureException
exceptions.Exception
exceptions.BaseException
__builtin__.object

Methods defined here:
__init__(self, message)
__str__(self)

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)
message

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args

 
class StreamCollector(threading.Thread)
    Collects from a stream into a string, and optionally also copies
into another stream.
 
 
Method resolution order:
StreamCollector
threading.Thread
threading._Verbose
__builtin__.object

Methods defined here:
__init__(self, fromStream, toStream=None, flushToStream=False, slowDown=0.0)
Create new StreamCollector thread.
 
Can be join()ed to wait until the thread terminates.
run(self)

Data descriptors defined here:
collected
A string containing all text that has been written to the stream.

Methods inherited from threading.Thread:
__repr__(self)
getName(self)
isAlive(self)
Return whether the thread is alive.
 
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
isDaemon(self)
is_alive = isAlive(self)
Return whether the thread is alive.
 
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
join(self, timeout=None, balancing=True)
Wait until the thread terminates.
 
This blocks the calling thread until the thread whose join() method is
called terminates -- either normally or through an unhandled exception
or until the optional timeout occurs.
 
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As join() always returns None, you must call
isAlive() after join() to decide whether a timeout happened -- if the
thread is still alive, the join() call timed out.
 
When the timeout argument is not present or None, the operation will
block until the thread terminates.
 
A thread can be join()ed many times.
 
join() raises a RuntimeError if an attempt is made to join the current
thread as that would cause a deadlock. It is also an error to join() a
thread before it has been started and attempts to do so raises the same
exception.
setDaemon(self, daemonic)
setName(self, name)
start(self)
Start the thread's activity.
 
It must be called at most once per thread object. It arranges for the
object's run() method to be invoked in a separate thread of control.
 
This method will raise a RuntimeError if called more than once on the
same thread object.

Data descriptors inherited from threading.Thread:
daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False).
 
This must be set before start() is called, otherwise RuntimeError is
raised. Its initial value is inherited from the creating thread; the
main thread is not a daemon thread and therefore all threads created in
the main thread default to daemon = False.
 
The entire Python program exits when no alive non-daemon threads are
left.
ident
Thread identifier of this thread or None if it has not been started.
 
This is a nonzero integer. See the thread.get_ident() function. Thread
identifiers may be recycled when a thread exits and another thread is
created. The identifier is available even after the thread has exited.
name
A string used for identification purposes only.
 
It has no semantics. Multiple threads may be given the same name. The
initial name is set by the constructor.

Data descriptors inherited from threading._Verbose:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)