当我在 Python 中调用外部.exe
程序时,如何printf
从应用程序获取输出.exe
并将其打印到我的 Python IDE?
user53670
问问题
36085 次
2 回答
25
要从 Python 调用外部程序,请使用subprocess模块。
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) '
>>>
于 2009-04-14T15:09:02.113 回答
7
我很确定您在这里谈论的是 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() 来获取状态或仅输出。
于 2009-04-14T15:38:55.490 回答