When I call an external .exe
program in Python, how can I get printf
output from the .exe
application and print it to my Python IDE?

- 11,218
- 8
- 50
- 99
3 Answers
To call an external program from Python, use the subprocess module.
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
An example from the doc (output
is a file object that provides output from the child process.):
output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0]
A concrete example, using cmd
, the Windows command line interpreter with 2 arguments:
>>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE)
>>> p1.communicate()[0]
'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) '
>>>
-
No, don't use os.popen(), it's been obsoleted by subprocess. – unwind Apr 14 '09 at 15:27
-
then how can I set the enviorment variables in this condition?myarg is the env var? – Apr 14 '09 at 15:45
-
No, 'myarg' is argument to the command 'mycmd'. You can pass an environment using the 'env' keyword argument. Give it a dictionary containing the environment you want to use. – Fred Larson Apr 14 '09 at 17:35
-
use subprocess.Popen([.....], stdout=..., env="YOUR ENV DICTIONARY") See: http://stackoverflow.com/questions/2231227/python-subprocess-popen-with-a-modified-environment – 0fnt Feb 21 '11 at 13:41
-
2In Python 3 you may want to use `...communicate()[0].decode()` to get the the actual `string` output, and not the `byte` output. – Phil-ZXX Nov 22 '20 at 20:31
-
i have a compile c application which I am running on linux environment. It is a huge code fetching data from sensors in while loop. Does the example stated above be able to fetch the data from that c application as well or "Only" those applications which gets terminated (returnd from main - return 0 or some exit code) – Raulp Feb 16 '22 at 11:16
I am pretty sure that you are talking about Windows here (based on the phrasing of your question), but in a Unix/Linux (including Mac) environment, the commands module is also available:
import commands
( stat, output ) = commands.getstatusoutput( "somecommand" )
if( stat == 0 ):
print "Command succeeded, here is the output: %s" % output
else:
print "Command failed, here is the output: %s" % output
The commands module provides an extremely simple interface to run commands and get the status (return code) and the output (reads from stdout and stderr). Optionally, you can get just status or just output by calling commands.getstatus() or commands.getoutput() respectively.

- 7,518
- 3
- 26
- 33
-
The answer above applies to python2, in python3 getstatusoutput and getoutput can be found in subprocess. – tssch Jul 20 '15 at 09:29
you can use subprocess.check_output(['mycmd', 'myargs'])
Example:
import subprocess
print(subprocess.check_output(['ls', '-1']).decode())

- 1,111
- 1
- 16
- 29