windows 从 Python 脚本中运行另一个程序的推荐方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/910733/
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
Recommended way to run another program from within a Python script
提问by Frederick The Fool
Possible Duplicate:
How to call external command in Python
可能的重复:
如何在 Python 中调用外部命令
I'm writing a Python script on a windows machine. I need to launch another application "OtherApp.exe". What is the most suitable way to do so?
我正在 Windows 机器上编写 Python 脚本。我需要启动另一个应用程序“OtherApp.exe”。什么是最合适的方法?
Till now I've been looking at os.system()
or os.execl()
and they don't quite look appropriate (I don't even know if the latter will work in windows at all).
直到现在我一直在看os.system()
oros.execl()
并且它们看起来不太合适(我什至不知道后者是否可以在 Windows 中工作)。
回答by Aaron Digulla
The recommended way is to use the subprocess module. All other ways (like os.system()
or exec
) are brittle, unsecure and have subtle side effects that you should not need to care about. subprocess replaces all of them.
推荐的方法是使用subprocess 模块。所有其他方式(如os.system()
或exec
)都是脆弱的、不安全的,并且具有您不需要关心的微妙副作用。subprocess 替换了所有这些。
回答by Dennis
Note that this answer is specific to python versions 2.x which I am locked to due to an embedded system. I am only leaving it for historical reasons just in case.
请注意,此答案特定于由于嵌入式系统而被锁定的 python 版本 2.x。我只是出于历史原因才离开它以防万一。
One of the things the subprocess offers is a method to catch the output of a command, for example using [popen] on a windows machine
子进程提供的一件事是一种捕获命令输出的方法,例如在 Windows 机器上使用 [popen]
import os
os.popen('dir').read()
will yield
会屈服
' Volume in drive C has no label.\n Volume Serial Number is 54CD-5392\n\n Directory of C:\Python25\Lib\site-packages\pythonwin\n\n[.] [..] dde.pyd license.txt\nPythonwin.exe [pywin] scintilla.dll tmp.txt\nwin32ui.pyd win32uiole.pyd \n 7 File(s) 984,178 bytes\n 3 Dir(s) 30,539,644,928 bytes free\n'
' 驱动器 C 中的卷没有标签。\n 卷序列号是 54CD-5392\n\n C:\Python25\Lib\site-packages\pythonwin\n\n[.] [..] dde.pyd 的目录license.txt\nPythonwin.exe [pywin] scintilla.dll tmp.txt\nwin32ui.pyd win32uiole.pyd \n 7 File(s) 984,178 bytes\n 3 Dir(s) 30,539,644,928 bytes free\n'
Which can then be parsed or manipulated any way you want.
然后可以以任何您想要的方式解析或操作它。