I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use subprocess.popen
or something similar but I'm new to subprocess and have no clue. Anyone have an easy way for me to get this done?
Asked
Active
Viewed 1.6k times
12

Adam Stelmaszczyk
- 19,665
- 4
- 70
- 110

Tyler
- 3,919
- 7
- 27
- 26
2 Answers
28
@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
while True:
out = process.stdout.readline(1)
if out == '' and process.poll() != None:
break
if out.startswith('myline'):
sys.stdout.write(out)
sys.stdout.flush()

Nadia Alramli
- 111,714
- 37
- 173
- 152
-
1what is `myline` here? – Hamza Rashid May 10 '18 at 08:12
-
The OP said _"I need a certain line printed out to the screen"_, `myline` was just an example. That portion of the code is where one would identify the specific line of output to print. – Alex Jul 10 '19 at 21:20
22
Something like this:
import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]

Paolo Bergantino
- 480,997
- 81
- 517
- 436
-
How would i read a certain line out? is that where the 0 is? And yes I'm interested in printing output after process is finished. Also where you have "yourcommand" does the exe extension go there? – Tyler May 28 '09 at 20:57
-
1"result" will be the entire output of "yourcommand". You can then process that string (or bytes object, in Py3.0) to find the line you're looking for. – Dietrich Epp May 28 '09 at 21:08
-
3the [0] means the first element of the tuple returned (stdout, stderr); you may process result, which will be a string, to your liking, e.g. to find a particular line. "yourcommand" is your full command, eventually a full path to a command if the command ist not *on path* (at least on *nix). – miku May 28 '09 at 21:08