Python subprocess subprocess with timeout

Hello I have such a problem, I need to execute some command and wait for its output, but before reading the output I need to write \n

to pipe. This is a unitest, so in some cases the command witch me test is not responding and my test test stops at stdout.readline()

and waits for something. So my question is, is it possible to set something like a timeout on the read line.

cmd = ['some', 'list', 'of', 'commands']
fp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fp.stdin.write('\n')
fp.stdout.readline()
out, err = fp.communicate()

      

+3


source to share


2 answers


Waiting for a response no more than a second:

from subprocess import Popen, PIPE

p = Popen(['command', 'the first argument', 'the second one', '3rd'],
          stdin=PIPE, stdout=PIPE, stderr=PIPE,
          universal_newlines=True)
out, err = p.communicate('\n', timeout=1) # write newline

      



The timeout feature is available in Python 2.x through http://pypi.python.org/pypi/subprocess32/ backport of subprocess 3.2+ module. See subprocess with timeout .

For solutions that use streams, signal.alarm, select, iocp, twisted, or just a temporary file, see the links to the relevant posts for your question.

+1


source


You pass the input directly for communication, https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate , from the docs

Interacting with the process: sending data to stdin. Reading data from standard stderr until end of file is reached. Wait for the process to complete. The optional input argument must be a string to be sent to the child to the process, or None if no data is to be sent to the child.



Example:

cmd = ['some', 'list', 'of', 'commands']
fp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = fp.communicate('\n')

      

0


source







All Articles