推荐的方法从Python脚本中运行另一个程序[重复]

时间:2022-04-21 01:14:57

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()或os.execl(),它们看起来不太合适(我甚至不知道后者是否会在Windows中工作)。

2 个解决方案

#1


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.

建议的方法是使用子进程模块。所有其他方式(如os.system()或exec)都是脆弱的,不安全的,并且具有您不应该关心的微妙副作用。 subprocess替换所有这些。

#2


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文件984,178字节\ n 3目录30,539,644,928字节免费\ n'

Which can then be parsed or manipulated any way you want.

然后可以以任何方式解析或操作。

#1


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.

建议的方法是使用子进程模块。所有其他方式(如os.system()或exec)都是脆弱的,不安全的,并且具有您不应该关心的微妙副作用。 subprocess替换所有这些。

#2


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文件984,178字节\ n 3目录30,539,644,928字节免费\ n'

Which can then be parsed or manipulated any way you want.

然后可以以任何方式解析或操作。