Python's subprocess module provides a way to execute external commands in a Python program. It allows us to interact with the operating system's command line and control and reference the output and behavior of external programs through code. This article will introduce how to use the subprocess module to execute external commands and provide some practical code examples.
To execute simple external commands, you can use the subprocess.call()
function of the subprocess module. This function will return the command's exit status code after executing the external command.
import subprocess # 执行一个简单的外部命令:获取当前目录下的文件列表 subprocess.call('ls')
If you want to get the output of an external command, you can use the subprocess.check_output()
function. This function executes the external command and returns its output as the function's return value.
import subprocess # 执行外部命令:获取当前目录下的文件列表 output = subprocess.check_output('ls') print(output)
Sometimes, we need to pass input data to external commands, or get real-time output from external commands. The subprocess module provides the Popen
class to meet these needs.
import subprocess # 执行外部命令:使用cat命令将输入数据输出到标准输出 input_data = b'Hello, World!' process = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output, error = process.communicate(input=input_data) print(output)
When the parameters of an external command contain spaces, the entire command needs to be passed to as a string subprocess.call()
or subprocess.check_output()
function.
import subprocess # 执行外部命令:计算一个数的平方 number = 10 subprocess.call('python -c "print({}**2)"'.format(number), shell=True)
When executing external commands, some errors may occur, such as the command does not exist or the command execution fails. We can use try-except statement to handle these errors.
import subprocess # 执行外部命令:命令不存在 try: subprocess.check_output('nonexistent_command') except subprocess.CalledProcessError as e: print('Command execution failed:', e)
These sample codes show how to use the subprocess module to execute external commands. Using the subprocess module allows us to easily interact with the command line and flexibly control the behavior of external programs. Whether it is a simple command or a complex task, the subprocess module can help us achieve it.
The above is the detailed content of How to use the subprocess module to execute external commands in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!