python子进程异常结束


Python subprocess module provides easy functions that allow us to spawn a new process and get their return codes. This module was introduced in Python v2.4.

Python子流程模块提供了简单的功能,这些功能使我们可以生成新流程并获取其返回代码。 该模块是Python v2.4中引入的。

In this lesson, we will study various functions available with the subprocess module and how we can put them to use.

在本课程中,我们将研究subprocess模块可用的各种功能以及如何使用它们。





(Python subprocess)

Python subprocess module is a powerful tool and was introduced to replace various old modules/functions present in Python, like:

Python子进程模块是一个功能强大的工具,被引入以替换Python中存在的各种旧模块/函数,例如:

Please note that replacements were not as is and some modifications in the program were needed to move to the subprocess module usage. Let’s start our journey with the functions of this module.

请注意,替换不是一样,并且需要对程序进行一些修改才能移至subprocess模块的用法。 让我们从该模块的功能开始我们的旅程。

(Python subprocess call())

This function is used to run a command and get the return code of the command. Let’s quickly look at an example code snippet:

此函数用于运行命令并获取命令的返回码。 让我们快速看一下示例代码片段:

import subprocess
print(subprocess.call(["pwd", "-P"]))

The output will be:




python Process进程的返回结果 python process finished_深度学习


输出将是:


Let’s understand what happened in above program:

让我们了解以上程序发生了什么:

  • When an argument list is passed, the first argument is interpreted as the executable.
  • The parameters from second param onwards are treated as the command line arguments to the program.
  • We could also have done:
import subprocess
print(subprocess.call('ls -l', shell=True))

With shell being True, call() function treats this as command completely and run it as is. The output would have shown all files and directories in current folder.

在shell为True的情况下, call()函数将其完全视为命令并按原样运行。 输出将显示当前文件夹中的所有文件和目录。

Note that in POSIX based systems, a 0 return code is for success and 1 to 255 are for anything else. These exit codes are interpreted by machine scripts to evaluate the events of success and failures.

请注意,在基于POSIX的系统中,返回码0表示成功,而1到255表示其他任何东西。 这些退出代码由机器脚本解释,以评估成功和失败的事件。

(Python subprocess run())

This function works just like the call method and is used to run a command and get the return code of the command. Let’s quickly look at an example code snippet:

该函数的工作方式与call方法类似,用于运行命令并获取命令的返回码。 让我们快速看一下示例代码片段:

import subprocess
print(subprocess.run(["pwd", "-P"]))

The output will be:


python Process进程的返回结果 python process finished_linux_02


输出将是:

Note that the run() function was added in Python 3.5. A clear difference between the run() and the call() function is that the call() function doesn’t supports the input and check parameters.

请注意, run()函数是在Python 3.5中添加的。 run()call()函数之间的明显区别是call()函数不支持输入和检查参数。

(Python subprocess check_call())

This function works like call() function but if there was an error in running the specified command, it raises a CalledProcessError exception. Let’s quickly look at an example code snippet:

该函数的功能类似于call()函数,但是如果在运行指定命令时出错,则会引发CalledProcessError异常。 让我们快速看一下示例代码片段:


import subprocess
print(subprocess.check_call("false"))

The output will be:


python Process进程的返回结果 python process finished_java_03


输出将是:

We used the false command as it always return with an error return code.

我们使用false命令,因为它总是返回错误返回码。

(Python subprocess check_output())

When we use the call() function to run a command, the output is bound to the parent process and is unretrievable for the calling program. We can use the check_output() function to capture the output for later usage. Let’s quickly look at an example code snippet:

当我们使用call()函数运行命令时,输出将绑定到父进程,并且对于调用程序是不可检索的。 我们可以使用check_output()函数捕获输出以供以后使用。 让我们快速看一下示例代码片段:

import subprocess
output = subprocess.check_output(['ls', '-1'])
print("Output is {} bytes long.".format(len(output)))

The output will be:


python Process进程的返回结果 python process finished_深度学习_04


输出将是:

(Python subprocess communicate())

We can use the communicate() function in this Python module to read input and the output forom the process itself. stdout is the process output and stderr is populated in case of an error. Let’s quickly look at an example code snippet:

我们可以在此Python模块中使用communicate()函数来读取输入和输出,以形成流程本身。 stdout是进程输出,如果发生stderr则填充stderr 。 让我们快速看一下示例代码片段:

import subprocess
process = subprocess.Popen(
    ['cat', 'hello.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout)

The output will be:


python Process进程的返回结果 python process finished_python_05


输出将是:

Note that we have a hello.py script which just says print("Hello").

请注意,我们有一个hello.py脚本, hello.py print("Hello")

(Python subprocess Popen)

Python subprocess Popen is used to execute a child program in a new process. We can use it to run some shell commands. Let’s look at Popen usage through simple example program.

Python子进程Popen用于在新进程中执行子程序。 我们可以使用它来运行一些shell命令。 让我们通过简单的示例程序来了解Popen的用法。

import subprocess

process = subprocess.Popen(['ls', '-ltr'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print(process.communicate())

process = subprocess.Popen(['echo', 'Pankaj'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=None)

print(process.communicate())

process = subprocess.Popen(['ping', '-c 1', 'journaldev.com'], stdout=subprocess.PIPE)

print(process.communicate())

When executed, it produces following output.

执行后,将产生以下输出。

(b'total 8\n-rw-r--r--  1 pankaj  staff  396 Dec  9 22:00 subprocess_popen.py\n', b'')
(b'Pankaj\n', b'')
(b'PING journaldev.com (209.124.77.163): 56 data bytes\n64 bytes from 209.124.77.163: icmp_seq=0 ttl=53 time=474.153 ms\n\n--- journaldev.com ping statistics ---\n1 packets transmitted, 1 packets received, 0.0% packet loss\nround-trip min/avg/max/stddev = 474.153/474.153/474.153/0.000 ms\n', None)

In this lesson, we learned about various functions provided by subprocess module in Python and saw how they work.

在本课程中,我们学习了Python子进程模块提供的各种功能,并了解了它们如何工作。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17416/python-subprocess

python子进程异常结束