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()
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Mike Minaev
  • 1,912
  • 4
  • 23
  • 33
  • related: [Non-blocking read on a subprocess.PIPE in python](http://stackoverflow.com/q/375427/4279) – jfs Dec 24 '14 at 16:37
  • related: [subprocess with timeout](http://stackoverflow.com/a/12698328/4279) – jfs Dec 24 '14 at 16:41
  • related: [Stop reading process output in Python without hang?](http://stackoverflow.com/a/4418891/4279) – jfs Dec 24 '14 at 16:42

2 Answers2

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
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')
user590028
  • 11,364
  • 3
  • 40
  • 57
  • 1
    it doesn't address *"is it possible to set something like timeout to reading line."* part of the question. – jfs Dec 24 '14 at 16:46