【问题标题】:How to get output of exe in python script?如何在python脚本中获取exe的输出?
【发布时间】:2010-10-19 09:09:11
【问题描述】:

当我在 Python 中调用外部 .exe 程序时,如何从 .exe 应用程序获取 printf 输出并将其打印到我的 Python IDE?

【问题讨论】:

    标签: python ide executable redirect


    【解决方案1】:

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

    【讨论】:

    • 不,不要使用 os.popen(),它已经被子进程淘汰了。
    • 那么在这种情况下如何设置环境变量?myarg 是环境变量?
    • 不,'myarg' 是命令 'mycmd' 的参数。您可以使用“env”关键字参数传递环境。给它一个包含您要使用的环境的字典。
    • 使用 subprocess.Popen([.....], stdout=..., env="YOUR ENV DICTIONARY") 见:stackoverflow.com/questions/2231227/…
    • 在 Python 3 中,您可能希望使用 ...communicate()[0].decode() 来获取实际的 string 输出,而不是 byte 输出。
    【解决方案2】:

    我很确定您在这里谈论的是 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() 来获取状态或仅输出。

    【讨论】:

    • 以上答案适用于python2,在python3中getstatusoutput和getoutput可以在子进程中找到。
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2017-12-30
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2015-08-24
    • 2012-02-01
    • 2020-08-18
    相关资源
    最近更新 更多