python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python中subprocess模块详解

Python中的subprocess模块用法及注意事项详解

作者:何曾参静谧

这篇文章主要介绍了Python中subprocess模块用法及注意事项的相关资料,Python subprocess模块用于运行外部命令,支持run()和Popen()方法,提供输入输出管理、环境变量设置等高级功能,需要的朋友可以参考下

前言

在Python编程中,经常需要执行外部命令或脚本。Python标准库中的subprocess模块提供了丰富的功能,允许你启动新的进程、连接到它们的输入/输出/错误管道,并获取它们的返回码。本文将详细介绍subprocess模块的使用方法,包括基本用法、高级功能以及一些注意事项。

一、基本用法

1.1 使用subprocess.run()

subprocess.run()是Python 3.5及以上版本中引入的一个高级接口,用于运行子进程并等待其完成。它返回一个CompletedProcess实例,其中包含进程的返回码、标准输出和标准错误输出。

import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(f'Return code: {result.returncode}')
print(f'Output:\n{result.stdout}')
print(f'Error:\n{result.stderr}')

1.2 使用subprocess.Popen()

subprocess.Popen()提供了更灵活的方式来启动和管理子进程。它返回一个Popen对象,允许你与子进程进行更复杂的交互。

import subprocess

process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
print(f'Return code: {process.returncode}')
print(f'Output:\n{stdout}')
print(f'Error:\n{stderr}')

二、高级功能

2.1 管理输入和输出

你可以通过Popen对象的stdinstdoutstderr属性与子进程进行交互。

import subprocess

process = subprocess.Popen(['grep', 'pattern'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
output, error = process.communicate(input='line with pattern\nanother line\n')
print(f'Return code: {process.returncode}')
print(f'Output:\n{output}')
print(f'Error:\n{error}')

2.2 设置环境变量

你可以通过env参数为子进程设置环境变量。

import subprocess
import os

env = os.environ.copy()
env['MY_VAR'] = 'my_value'
result = subprocess.run(['printenv', 'MY_VAR'], env=env, capture_output=True, text=True)
print(result.stdout)

2.3 捕获子进程的输出而不阻塞

你可以使用Popen对象的stdoutstderr文件的readline()read()方法来逐步读取输出,而不是一次性等待所有输出完成。

import subprocess

process = subprocess.Popen(['ls', '-l', '/some/large/directory'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

while True:
    line = process.stdout.readline()
    if not line:
        break
    print(line.strip())

process.wait()  # 等待进程结束

三、注意事项

四、总结

subprocess模块是Python中处理外部命令和脚本的强大工具。通过subprocess.run()subprocess.Popen(),你可以以灵活和强大的方式启动和管理子进程。掌握这些工具将使你能够编写更加复杂和健壮的Python程序。

到此这篇关于Python中的subprocess模块用法及注意事项的文章就介绍到这了,更多相关Python中subprocess模块详解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文