Using the Module The recommended approach to invoking subprocesses is to use the function for all use cases it can handle. For more advanced use cases, the underlying interface can be used directly. The function was added in Python 3.5; if you need to retain compatibility with older versions, see the section. Run ( args,., stdin=None, input=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None ) Run the command described by args. Wait for command to complete, then return a instance. The arguments shown above are merely the most common ones, described below in (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.
This does not capture stdout or stderr by default. To do so, pass for the stdout and/or stderr arguments.
Python's subprocess module provides several methods of running external programs. It's easy to use, but. '%s'% (str(e))). ( download check-output-shell.py ). The Subprocess Module Python Tutorial So this tutorial is a lot more than just the sample code. While you probably can just get by with the others without watching the video, this one is going to probably make no sense without the video.
The timeout argument is passed to. If the timeout expires, the child process will be killed and waited for. The exception will be re-raised after the child process has terminated. The input argument is passed to and thus to the subprocess’s stdin.
If used it must be a byte sequence, or a string if encoding or errors is specified or universalnewlines is true. When used, the internal object is automatically created with stdin=PIPE, and the stdin argument may not be used as well. If check is true, and the process exits with a non-zero exit code, a exception will be raised.
Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured. If encoding or errors are specified, or universalnewlines is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the default. Otherwise, file objects are opened in binary mode. subprocess. Run ( 'ls', '-l' ) # doesn't capture output CompletedProcess(args='ls', '-l', returncode=0) subprocess.
Run ( 'exit 1', shell = True, check = True ) Traceback (most recent call last). Subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 subprocess. Run ( 'ls', '-l', '/dev/null' , stdout = subprocess. PIPE ) CompletedProcess(args='ls', '-l', '/dev/null', returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null n'). Changed in version 3.6: Added encoding and errors parameters class subprocess. CompletedProcess The return value from, representing a process that has finished.
Args The arguments used to launch the process. This may be a list or a string. Returncode Exit status of the child process.
Typically, an exit status of 0 indicates that it ran successfully. A negative value -N indicates that the child was terminated by signal N (POSIX only). Stdout Captured stdout from the child process. A bytes sequence, or a string if was called with an encoding or errors. None if stdout was not captured. If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and will be None.
Stderr Captured stderr from the child process. A bytes sequence, or a string if was called with an encoding or errors. None if stderr was not captured. Checkreturncode ( ) If is non-zero, raise a.
Changed in version 3.5: stdout and stderr attributes added exception subprocess. CalledProcessError Subclass of, raised when a process run by or returns a non-zero exit status.
Returncode Exit status of the child process. If the process exited due to a signal, this will be the negative signal number. Cmd Command that was used to spawn the child process. Output Output of the child process if it was captured. Otherwise, None. Stdout Alias for output, for symmetry with.
Stderr Stderr output of the child process if it was captured. Otherwise, None. Args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. To permit spaces in file names).
If passing a single string, either shell must be (see below) or else the string must simply name the program to be executed without specifying any arguments. Stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are, an existing file descriptor (a positive integer), an existing file object, and None.
Indicates that a new pipe to the child should be created. Indicates that the special file will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout. If encoding or errors are specified, or universalnewlines is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for. For stdin, line ending characters ' n' in the input will be converted to the default line separator.
For stdout and stderr, all line endings in the output will be converted to ' n'. For more information see the documentation of the class when the newline argument to its constructor is None. If text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed. Note The newlines attribute of the file objects, and are not updated by the method. If shell is True, the specified command will be executed through the shell.
This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, and ). Popen Constructor The underlying process creation and management in this module is handled by the class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions. Class subprocess.
Popen ( args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexecfn=None, closefds=True, shell=False, cwd=None, env=None, universalnewlines=False, startupinfo=None, creationflags=0, restoresignals=True, startnewsession=False, passfds=,., encoding=None, errors=None ) Execute a child program in a new process. On POSIX, the class uses -like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess function. The arguments to are as follows. Args should be a sequence of program arguments or else a single string.
By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute.
However, this can only be done if not passing arguments to the program. import shlex, subprocess commandline = input /bin/vikings -input eggs.txt -output 'spam spam.txt' -cmd 'echo '$MONEY' args = shlex. Split ( commandline ) print ( args ) '/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', 'echo '$MONEY' p = subprocess. Popen ( args ) # Success! Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. On Windows, if args is a sequence, it will be converted to a string in a manner described in.
This is because the underlying CreateProcess operates on strings. The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, does the equivalent of.
Note Read the section before using shell=True. Bufsize will be supplied as the corresponding argument to the function when creating the stdin/stdout/stderr pipe file objects:. 0 means unbuffered (read and write are one system call and can return short). 1 means line buffered (only usable if universalnewlines=True i.e., in a text mode). any other positive value means use a buffer of approximately that size. negative bufsize (the default) means the system default of io.DEFAULTBUFFERSIZE will be used.
![Import Import](http://1.bp.blogspot.com/-jIdrl-FCYp0/U0hauhN-SLI/AAAAAAAAAYw/uIizg2Pxw14/s1600/simplestcall.png)
Changed in version 3.3.1: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected. The executable argument specifies a replacement program to execute. It is very seldom needed.
When shell=False, executable replaces the program to execute specified by args. However, the original args is still passed to the program. Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On POSIX, the args name becomes the display name for the executable in utilities such as ps. If shell=True, on POSIX the executable argument specifies a replacement shell for the default /bin/sh.
Stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are, an existing file descriptor (a positive integer), an existing, and None. Indicates that a new pipe to the child should be created. Indicates that the special file will be used.
With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexecfn is set to a callable object, this object will be called in the child process just before the child is executed.
(POSIX only). Note If you need to modify the environment for the child use the env parameter rather than doing it in a preexecfn. The startnewsession parameter can take the place of a previously common use of preexecfn to call os.setsid in the child.
If closefds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (POSIX only). The default varies by platform: Always true on POSIX.
On Windows it is true when stdin/ stdout/ stderr are, false otherwise. On Windows, if closefds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set closefds to true and also redirect the standard handles by setting stdin, stdout or stderr. Exceptions Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called childtraceback, which is a string containing traceback information from the child’s point of view. The most common exception raised is. This occurs, for example, when trying to execute a non-existent file.
Applications should prepare for exceptions. A will be raised if is called with invalid arguments. And will raise if the called process returns a non-zero return code. All of the functions and methods that accept a timeout parameter, such as and will raise if the timeout expires before the process exits. Exceptions defined in this module all inherit from. Security Considerations Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes.
If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid vulnerabilities. When using shell=True, the function can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands. Deprecated since version 3.4: Do not use the endtime parameter. It is was unintentionally exposed in 3.3 but was left undocumented as it was intended to be private for internal use. Use timeout instead.
Communicate ( input=None, timeout=None ) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.
Wait for process to terminate. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child.
If streams were opened in text mode, input must be a string. Otherwise, it must be bytes. Returns a tuple (stdoutdata, stderrdata). The data will be strings if streams were opened in text mode; otherwise, bytes. Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
If the process does not terminate after timeout seconds, a exception will be raised. Catching this exception and retrying communication will not lose any output. The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication.
Note On Windows, SIGTERM is an alias for. CTRLCEVENT and CTRLBREAKEVENT can be sent to processes started with a creationflags parameter which includes CREATENEWPROCESSGROUP. Terminate ( ) Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess is called to stop the child. Kill ( ) Kills the child.
On Posix OSs the function sends SIGKILL to the child. On Windows is an alias for. The following attributes are also available: Popen. Args The args argument as it was passed to – a sequence of program arguments or else a single string.
New in version 3.3. Stdin If the stdin argument was, this attribute is a writeable stream object as returned. If the encoding or errors arguments were specified or the universalnewlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was not, this attribute is None. Stdout If the stdout argument was, this attribute is a readable stream object as returned.
Reading from the stream provides output from the child process. If the encoding or errors arguments were specified or the universalnewlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not, this attribute is None.
Stderr If the stderr argument was, this attribute is a readable stream object as returned. Reading from the stream provides error output from the child process.
If the encoding or errors arguments were specified or the universalnewlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was not, this attribute is None. Si = subprocess.
STARTUPINFO si. DwFlags = subprocess.
STARTFUSESTDHANDLES subprocess. STARTFUSESHOWWINDOW hStdInput If specifies, this attribute is the standard input handle for the process.
If is not specified, the default for standard input is the keyboard buffer. HStdOutput If specifies, this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer. HStdError If specifies, this attribute is the standard error handle for the process.
Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer. WShowWindow If specifies, this attribute can be any of the values that can be specified in the nCmdShow parameter for the function, except for SWSHOWDEFAULT. Otherwise, this attribute is ignored. Is provided for this attribute. It is used when is called with shell=True.
Constants The module exposes the following constants. STDINPUTHANDLE The standard input device.
Initially, this is the console input buffer, CONIN$. STDOUTPUTHANDLE The standard output device. Initially, this is the active console screen buffer, CONOUT$. STDERRORHANDLE The standard error device. Initially, this is the active console screen buffer, CONOUT$. SWHIDE Hides the window.
Another window will be activated. STARTFUSESTDHANDLES Specifies that the, and attributes contain additional information.
STARTFUSESHOWWINDOW Specifies that the attribute contains additional information. CREATENEWCONSOLE The new process has a new console, instead of inheriting its parent’s console (the default). CREATENEWPROCESSGROUP A creationflags parameter to specify that a new process group will be created. This flag is necessary for using on the subprocess.
This flag is ignored if is specified. Run (., check = True, stdout = PIPE ). Stdout The arguments shown above are merely the most common ones. The full function signature is largely the same as that of - most arguments are passed directly through to that interface. However, explicitly passing input=None to inherit the parent’s standard input file handle is not supported. By default, this function will return the data as encoded bytes.
The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting universalnewlines to True as described above in. To also capture standard error in the result, use stderr=subprocess.STDOUT. ( childstdout, childstdin ) = popen2. Popen2 ( 'mycmd', 'myarg' , bufsize, mode ) p = Popen ( 'mycmd', 'myarg' , bufsize = bufsize, stdin = PIPE, stdout = PIPE, closefds = True ) ( childstdout, childstdin ) = ( p.
Stdin ) popen2.Popen3 and popen2.Popen4 basically work as, except that:. raises an exception if the execution fails. the capturestderr argument is replaced with the stderr argument. stdin=PIPE and stdout=PIPE must be specified. popen2 closes all file descriptors by default, but you have to specify closefds=True with to guarantee this behavior on all platforms or past Python versions. Legacy Shell Invocation Functions This module also provides the following legacy functions from the 2.x commands module.
These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions. Getstatusoutput ( cmd ) Return (exitcode, output) of executing cmd in a shell. Execute the string cmd in a shell with Popen.checkoutput and return a 2-tuple (exitcode, output). The locale encoding is used; see the notes on for more details.
A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Converting an argument sequence to a string on Windows On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):.
Arguments are delimited by white space, which is either a space or a tab. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. Backslashes are interpreted literally, unless they immediately precede a double quotation mark. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.
The 'subprocess' module in Python 2.4 has made creating and accessing subprocess streams in Python relatively convenient for all supported platforms, but what if you want to interact with the started subprocess? That is, what if you want to send a command, read the response, and send a new command based on that response? Now there is a solution. The included subprocess.Popen subclass adds three new commonly used methods: recv(maxsize=None), recverr(maxsize=None), and send(input), along with a utility method: sendrecv(input=', maxsize=None).
Recv and recverr both read at most maxsize bytes from the started subprocess. Send sends strings to the started subprocess. Sendrecv will send the provided input, and read up to maxsize bytes from both stdout and stderr. If any of the pipes are closed, the attributes for those pipes will be set to None, and the methods will return None. 1.3 fixed a few bugs relating to.nix support v. 1.4,5 fixed initialization on all platforms, a few bugs relating to Windows support, added two utility functions, and added an example of how to use this module.
1.6 fixed linux recv and test initialization thanks to Yuri Takhteyev at Stanford. 1.7 removed setup and init and fixed subprocess unittests thanks to Antonio Valentino. Added 4th argument 'tr' to recvsome, which is, approximately, the number of times it will attempt to recieve data. Added 5th argument 'stderr' to recvsome, where when true, will recieve from stderr. Cleaned up some pipe closing. 1.8 Fixed missing self.
Parameter in non-windows recv method thanks to comment. 1.9 Fixed fcntl calls for closed handles. Import os import subprocess import errno import time import sys PIPE = subprocess.
PIPE if subprocess. Mswindows: from win32file import ReadFile, WriteFile from win32pipe import PeekNamedPipe import msvcrt else: import select import fcntl class Popen ( subprocess. Popen ): def recv ( self, maxsize = None ): return self. recv ( 'stdout', maxsize ) def recverr ( self, maxsize = None ): return self.
recv ( 'stderr', maxsize ) def sendrecv ( self, input = ', maxsize = None ): return self. Send ( input ), self.
Recv ( maxsize ), self. Recverr ( maxsize ) def getconnmaxsize ( self, which, maxsize ): if maxsize is None: maxsize = 1024 elif maxsize 0: ( errCode, read ) = ReadFile ( x, nAvail, None ) except ValueError: return self. close ( which ) except ( subprocess. Error, Exception ), why: if why 0 in ( 109, errno. ESHUTDOWN ): return self. close ( which ) raise if self.
Universalnewlines: read = self. translatenewlines ( read ) return read else: def send ( self, input ): if not self. Stdin: return None if not select. Select (self.
Stdin , , 0 ) 1 : return 0 try: written = os. Write ( self. Fileno , input ) except OSError, why: if why 0 errno. EPIPE: #broken pipe return self. close ( 'stdin' ) raise return written def recv ( self, which, maxsize ): conn, maxsize = self.
![Subprocess module python Subprocess module python](/uploads/1/2/5/5/125511410/663465588.jpg)
Getconnmaxsize ( which, maxsize ) if conn is None: return None flags = fcntl. Fcntl ( conn, fcntl. FGETFL ) if not conn. Closed: fcntl. Fcntl ( conn, fcntl.
FSETFL, flags os. ONONBLOCK ) try: if not select. Select ( conn , , , 0 ) 0 : return ' r = conn. Read ( maxsize ) if not r: return self. close ( which ) if self.
Universalnewlines: r = self. translatenewlines ( r ) return r finally: if not conn. Closed: fcntl. Fcntl ( conn, fcntl. FSETFL, flags ) message = 'Other end disconnected!'
Def recvsome ( p, t =. 1, e = 1, tr = 5, stderr = 0 ): if tr. In wxPython, one can use wxExecute and wxProcess to the same effect, though then one is required to use wxPython. With the above subclass, writing a multi-platform 'expect' module would be relatively straightforward.
I had originally used a variant of the above for running arbitrary commands in a version of PyPE. Ultimately I went with a wxExecute/wxProcess combination due to the convenience of being notified when a process terminates, not having to ship subprocess.py for use with Python 2.3, and not needing for Windows users to install pywin32. Both have an issue in that some commands will buffer their output strangely in Windows (though I have not observed such behavior on.nix, that doesn't mean that such platforms are immune). For example, running some python scripts via either method results in no observed output from python until python closes (even when a fairly large volume of data is printed via Python), neither cygwin bash nor sh display their prompts, etc. Possible alternative unix approach. I was successful using nonblocking io, for example. Flags = fcntl.fcntl(subprocess.stdout, fcntl.FGETFL) fcntl.fcntl(subprocess.stdout, fcntl.FSETFL, flags os.ONONBLOCK) Once the process instance is created change its stdout to nonblocking reads.
I am aware of one downside to this approach is the resource temporarily unavailable exceptions upon reading. These can be safely ignored.
Another may be the need to poll the subprocess, so I suspect the select method with 0 for the timeout is more appropriate. Long running processes. Nice piece of code. I was dealing with the output from a long running process and found recvsome would occasionally freeze. If the proc.recv happened to take long enough, time.time could be greater than x, which results in a negative argument for time.sleep. It apparently tries to sleep forever in this case. I just added a check: delay=(x-time.time)/5 if delay0: time.sleep(delay) Also, on Linux, I had to add 'import select'.
Nice work, though, definitely saved me some time. Can't capture child output. After adding 'import select', the code runs (SUSE 10). However, changing the line: shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), ' n') to shell, commands, tail = ('sh', ('./mttst.py'), ' n') results in an immediate error 'Other end disconnected!'
Mttst.py is executable and runs from the CL.! /usr/bin/python import time print 'mttst.py started' for i in range(5): the next two lines should be indented. Don't know how. Print time.time time.sleep(1) print 'mttst.py finished' Suggestions on what I'm doing wrong much appreciated. Standard subprocess unittest.
The setup method raises an exception if one of the stdin, stdout, stderr file descriptors is None. Setting non-blocking mode at sub-process startup (POSIX case) seems to break the unit tests (testsubproces.py) of the standard subprocess module. I set the non-blocking flag in send and recv methods and restore the original ones before they returns. Def recv(self, which, maxsize): conn, maxsize = self.getconnmaxsize(which, maxsize) if conn is None: return None flags = fcntl.fcntl(conn, fcntl.FGETFL) fcntl.fcntl(conn, fcntl.FSETFL, flags os.ONONBLOCK) try: if not select.select(conn, , , 0)0: return ' r = conn.read(maxsize) if not r: conn.close setattr(self, which, None) return None if self.universalnewlines: r = self.translatenewlines(r) return r finally: fcntl.fcntl(conn, fcntl.FSETFL, flags) This fixes the problem. The setup method now is no more needed. If you look at other pieces of the demo, it asumes each item run will execute almost instaneously. In this case, the program it is attempting to run takes around 5 seconds (plus the starting up of Python, which hopefully should be fast).
Even if it did run successfully, it wouldn't necessarily print everything as output (especially considering Python's sometimes wonky stdout buffering semantics on certain platforms). I tried running it on Windows, and it printed out the 'starting' message along with the first timestamp. Then it paused for 5 seconds waiting for the subprocess to close (while not recieving information), and quit without exception. Running your examples gives me a 'ValueError: I/O operation on closed file' When I run your example on Linux with Python 2.4.4 I get an exception. The stack dump is HELLO WORLD Traceback (most recent call last): File './aspn440554.py', line 167, in?
Print recvsome(a, e=0) File './aspn440554.py', line 136, in recvsome r = pr File './aspn440554.py', line 26, in recv return self.recv('stdout', maxsize) File './aspn440554.py', line 123, in recv fcntl.fcntl(conn, fcntl.FSETFL, flags) ValueError: I/O operation on closed file Changing the line 123 to if not conn.closed: fcntl.fcntl(conn, fcntl.FSETFL, flags) fixes the problem for me. I don't do much with Python, but recently needed to use this useful recipe. I found that I needed to add something to wait for a specific string to appear in the output prior to continuing. In looking at the output I needed to ignore the echo of the command I was sending to the shell, and only look at the output that results from the execution of the command. Here's what I added: def recvsomerestring(p, prog, t=.1, e=1, tr=5, stderr=0): if tr ' break else: time.sleep(max((x-time.time)/tr, 0)) return '.join(y) def doCommandAndWaitfor(cmd, response, t=.1, e=1, tr=5, stderr=0): sendall(a,cmd+tail) waitfor = '. R n.'
+cmd+'. R n.' +response prog = re.compile(waitfor) print recvsomerestring(a, prog, t, e, tr, stderr) (I just noticed that I have r n in the regular expression, so that needs to be fixed for portability to.nix systems).
Every sleep call is actually a waste of time, because sleeping IS implemented in the reactor (select), but not as 'sleep for N secs then check' but 'sleep until check', so the code can be easily refactored without any 'tries' count or 'sleep'. Below method is a piece of async wrapper class, just for reference. 'self.pollin' here is py2.6 epoll reactor object in level-triggering mode. Def read(self, bs=-1, to=-1, status=False): 'Read until timeout or size bs. Returns read buffer or (buffer, returncondition) if status flag is set.' ' if to 0 else self.bsdefault) # min for G+ reads buff += ext bs -= len(ext) to = deadline - time if to.