4

Hello i have such problem, i need to execute some command and wait for it's output, but before reading output i need to write \n to pipe. This the unitest, so in some cases command witch i test don't answer and my testcase stopping at stdout.readline() and waiting for smth. So my question is, is it possible to set something like timeout to reading 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

2 Answers 2

2

To wait for the 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 on Python 2.x via the http://pypi.python.org/pypi/subprocess32/ backport of the 3.2+ subprocess module. See subprocess with timeout.

For solutions that use threads, signal.alarm, select, iocp, twisted, or just a temporary file, see the links to the related posts under your question.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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 a string to be sent to the child process, or None, if no data should 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')

1 Comment

it doesn't address "is it possible to set something like timeout to reading line." part of the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.