python 运行外部程序_如何使用子流程在Python 3中运行外部程序

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)Py...
摘要由CSDN通过智能技术生成

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代码运行外部程序。 不过,首先,您需要将subprocesssys模块导入程序中:

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值