1

I have a python script which executes the following command using subprocess, but it gets stuck when some error occurs:

import subprocess
COMMAND = " Application.exe arg1 arg2"
process = subprocess.Popen(COMMAND, stdout=subprocess.PIPE, stderr=None, shell=True)

while process.poll() is None:
output = process.stdout.readline()
print output,

output:

There was a communication problem.
Failed.

Press enter to exit...

Because of the above output, my program is not able to exit until I press any key manually. Please help show me how to handle the above response and exit my code. The above program works good if there is no error.

Community
  • 1
  • 1
user1891916
  • 719
  • 1
  • 6
  • 8

1 Answers1

0

First, the last two lines of your code (within the while loop) need to be properly indented:

import subprocess
COMMAND = " Application.exe arg1 arg2"
process = subprocess.Popen(COMMAND, stdout=subprocess.PIPE, stderr=None, shell=True)

while process.poll() is None:
    output = process.stdout.readline()
    print output,

Second, if your COMMAND finishes too quickly, then your while loop may end before you've read the data completely. To remedy this issue, use the communicate() method:

output = process.communicate()[0]
print output,

Here are the docs related to Popen.communicate()

Daniel
  • 2,065
  • 3
  • 16
  • 34
  • My pleasure! Happy to help. – Daniel Aug 01 '15 at 17:52
  • @user1891916: [you don't need `.poll()` here](http://stackoverflow.com/a/17698359/4279) – jfs Aug 01 '15 at 23:49
  • @user1891916: I don't see how the answer could have possibly solved the *"Press enter to exit..."* issue. You need `stdin=DEVNULL` or `stdin=PIPE` and either `process.stdin.close()` or implicitly via `process.communicate()` (`.communicate()` without `stdin=PIPE` won't produce EOF on the application's stdin) – jfs Aug 01 '15 at 23:55