How to run external executable using Python?

落花浮王杯 提交于 2019-12-30 03:48:08

问题


I have an external executable file which i am trying to run from a Python script. CMD executable runs but without generating output. Probably it exit before output can be generated. Any suggestion about how to delay exit until outputs are generated?

import subprocess, sys
from subprocess import Popen, PIPE
exe_str = r"C:/Windows/System32/cmd C:/temp/calc.exe"

parent = subprocess.Popen(exe_str,  stderr=subprocess.PIPE)

回答1:


use subprocess.call, more info here:

import subprocess
subprocess.call(["C:\\temp\\calc.exe"])

or

import os
os.system('"C:/Windows/System32/notepad.exe"')

i hope it helps you...




回答2:


The os.system method is depreciated and should not be used in new applications. The subprocess module is the pythonic way to do what you require.

Here is an example of some code I wrote a few weeks ago using subprocess to load files, the command you need to use to delay exit until data has been received and the launched program completes is wait():

import subprocess

cmd = "c:\\file.exe"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000)
process.wait()

creationflags=0x08000000 is an optional parameter which suppresses the launch of a window, which can be useful if the program you are calling does not need to be directly seen.




回答3:


Option 1

import subprocess

subprocess.call('C:\Windows\System32\calc.exe')

Option 2

subprocess.Popen(['C:\Windows\System32\calc.exe'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).communicate()

Option 3

import os
os.system('C:\Windows\System32\calc.exe')



回答4:


This worked for me after trying everything else: Change the location of your python program to be the same as where the .exe is located. And then the simple:

subprocess.call("calc.exe") would work.



来源:https://stackoverflow.com/questions/13222808/how-to-run-external-executable-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!