How to use the subprocess module to execute external commands in Python 2.x

王林
Release: 2023-07-29 18:36:30
Original
902 people have browsed it

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.

  1. Execute simple external commands

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')
Copy after login
  1. Get the output of an external command

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)
Copy after login
  1. Control the input and output of external commands

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)
Copy after login
  1. Execute an external command whose command line parameters contain spaces

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)
Copy after login
  1. Add error handling

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!