如何使用python运行带有参数的exe文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15928956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to run an exe file with the arguments using python
提问by bappa147
Suppose I have a file RegressionSystem.exe. I want to execute this executable with a -configargument. The commandline should be like:
假设我有一个文件RegressionSystem.exe。我想用-config参数执行这个可执行文件。命令行应该是这样的:
RegressionSystem.exe -config filename
I have tried like:
我试过像:
regression_exe_path = os.path.join(get_path_for_regression,'Debug','RegressionSystem.exe')
config = os.path.join(get_path_for_regression,'config.ini')
subprocess.Popen(args=[regression_exe_path,'-config', config])
but it didn't work.
但它没有用。
回答by Rested
os.system("/path/to/exe/RegressionSystem.exe -config "+str(config)+" filename")
Should work.
应该管用。
回答by hjweide
You can also use subprocess.call()if you want. For example,
subprocess.call()如果你愿意,你也可以使用。例如,
import subprocess
FNULL = open(os.devnull, 'w') #use this if you want to suppress output to stdout from the subprocess
filename = "my_file.dat"
args = "RegressionSystem.exe -config " + filename
subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=False)
The difference between calland Popenis basically that callis blocking while Popenis not, with Popenproviding more general functionality. Usually callis fine for most purposes, it is essentially a convenient form of Popen. You can read more at this question.
call和之间的区别Popen基本上call是阻塞而Popen不是,Popen提供更通用的功能。通常call适用于大多数目的,它本质上是一种方便的Popen. 您可以在此问题中阅读更多内容。
回答by Daniel Butler
The accepted answer is outdated. For anyone else finding this you can now use subprocess.run(). Here is an example:
接受的答案已过时。对于发现此问题的任何其他人,您现在可以使用subprocess.run(). 下面是一个例子:
import subprocess
subprocess.run(["RegressionSystem.exe", "-config filename"])
The arguments can also be sent as a string instead, but you'll need to set shell=True. The official documentation can be found here.
参数也可以作为字符串发送,但您需要设置shell=True. 官方文档可以在这里找到。

