How to get output of exe in python script?

一世执手 提交于 2019-12-04 08:40:28

问题


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?


回答1:


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) '
>>> 



回答2:


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.



来源:https://stackoverflow.com/questions/748028/how-to-get-output-of-exe-in-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!