7 python ide executable redirect
当我.exe用Python 调用外部程序时,如何printf从.exe应用程序获取输出并将其打印到我的Python IDE中?
gim*_*mel 20
要从Python调用外部程序,请使用子进程模块.
子进程模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回代码.
doc中的一个示例(output是一个提供子进程输出的文件对象.):
output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
一个具体的例子,使用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) '
>>>
Run Code Online (Sandbox Code Playgroud)
我很确定你在这里谈论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
Run Code Online (Sandbox Code Playgroud)
命令模块提供了一个非常简单的接口来运行命令并获取状态(返回代码)和输出(从stdout和stderr读取).(可选)您可以通过分别调用commands.getstatus()或commands.getoutput()来获取状态或仅输出.