【发布时间】:2010-10-19 09:09:11
【问题描述】:
当我在 Python 中调用外部 .exe 程序时,如何从 .exe 应用程序获取 printf 输出并将其打印到我的 Python IDE?
【问题讨论】:
标签: python ide executable redirect
当我在 Python 中调用外部 .exe 程序时,如何从 .exe 应用程序获取 printf 输出并将其打印到我的 Python IDE?
【问题讨论】:
标签: python ide executable redirect
要从 Python 调用外部程序,请使用 subprocess 模块。
子进程模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。
文档中的一个示例(output 是一个提供子进程输出的文件对象。):
output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0]
一个具体的例子,使用cmd,带有2个参数的Windows命令行解释器:
>>> 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) '
>>>
【讨论】:
...communicate()[0].decode() 来获取实际的 string 输出,而不是 byte 输出。
我很确定您在这里谈论的是 Windows(基于您问题的措辞),但在 Unix/Linux(包括 Mac)环境中,命令模块也可用:
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
commands 模块提供了一个非常简单的接口来运行命令并获取状态(返回码)和输出(从 stdout 和 stderr 读取)。或者,您可以通过分别调用 commands.getstatus() 或 commands.getoutput() 来获取状态或仅输出。
【讨论】: