How to get output of exe in python script?

后端 未结 2 404
悲哀的现实
悲哀的现实 2021-02-04 15:09

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?

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 15:44

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

提交回复
热议问题