python 运行外部程序
The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.
作者选择了COVID-19救济基金来接受捐赠,这是Write for DOnations计划的一部分。
介绍 (Introduction)
Python 3 includes the subprocess
module for running external programs and reading their outputs in your Python code.
Python 3包含用于运行外部程序并读取您的Python代码中的输出的subprocess
模块 。
You might find subprocess
useful if you want to use another program on your computer from within your Python code. For example, you might want to invoke git
from within your Python code to retrieve files in your project that are tracked in git
version control. Since any program you can access on your computer can be controlled by subprocess
, the examples shown here will be applicable to any external program you might want to invoke from your Python code.
如果要从Python代码中使用计算机上的另一个程序,可能会发现subprocess
很有用。 例如,您可能想从Python代码中调用git
,以检索项目中在git
版本控制中跟踪的文件。 由于您可以在计算机上访问的任何程序都可以由subprocess
控制,因此此处显示的示例适用于您可能想从Python代码调用的任何外部程序。
subprocess
includes several classes and functions, but in this tutorial we’ll cover one of subprocess
’s most useful functions: subprocess.run
. We’ll review its different uses and main keyword arguments.
subprocess
包含几个类和函数,但是在本教程中,我们将介绍subprocess
最有用的功能之一: subprocess.run
。 我们将回顾其不同用途和主要关键字参数。
先决条件 (Prerequisites)
To get the most out of this tutorial, it is recommended to have some familiarity with programming in Python 3. You can review these tutorials for the necessary background information:
为了充分利用本教程,建议您熟悉Python 3的编程。您可以查看以下教程以获取必要的背景信息:
运行外部程序 (Running an External Program)
You can use the subprocess.run
function to run an external program from your Python code. First, though, you need to import the subprocess
and sys
modules into your program:
您可以使用subprocess.run
函数从Python代码运行外部程序。 不过,首先,您需要将subprocess
和sys
模块导入程序中:
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "print('ocean')"])
If you run this, you will receive output like the following:
如果运行此命令,将收到类似以下的输出:
Output
ocean
Let’s review this example:
让我们来看这个例子:
sys.executable
is the absolute path to the Python executable that your program was originally invoked with. For example,sys.executable
might be a path like/usr/local/bin/python
.