你是否曾好奇 AI 如何自动执行终端指令,无需人工干预?
又或者,如何实现自动化调用系统命令,让程序代替人工完成重复性操作?
如果你希望通过 Python 实现这些功能,那么 subprocess 模块将是你的得力助手。
subprocess 简介
subprocess 是 Python 中用于构建命令行交互和自动化任务的核心模块之一。它无需额外安装,是 Python 标准库的一部分,开箱即用。
示例
python
import subprocess
# 查看当前目录
result = subprocess.run(["cmd", "/c", "cd"])
print(f"返回码: {result.returncode}")
说明 : run() 是执行命令的核心函数,参数以列表形式传入,每个元素代表命令的一部分。执行结果可通过返回值获取。
基本用法
掌握以下几种典型用法,你就能应对大部分自动化场景:
python
import subprocess
# 1. 执行命令并获取返回码
result = subprocess.run(["cmd", "/c", "cd"])
print(f"返回码: {result.returncode}")
# 2. 捕获命令输出
result = subprocess.run(["cmd", "/c", "cd"],
capture_output=True,
text=True)
print(f"输出内容: {result.stdout}")
# 3. 设置超时控制
try:
result = subprocess.run(["powershell", "sleep", "10"],
timeout=2, # 2秒后超时
capture_output=True)
except subprocess.TimeoutExpired:
print("命令执行超时")
# 4. 严格检查执行结果(失败时抛出异常)
result = subprocess.run(["cmd", "/c", "cd", "nonexistent"],
capture_output=True,
text=True,
check=True) # 非零返回码将触发异常
执行效果:

进阶技巧
管道操作(Pipe)
管道可将前一个命令的输出作为下一个命令的输入,例如 A | B 表示将 A 的输出传递给 B。
python
netstat = subprocess.Popen(["netstat", "-ano"], stdout=subprocess.PIPE)
find = subprocess.Popen(
["findstr", "127.0.0.1:6379"],
stdin=netstat.stdout,
stdout=subprocess.PIPE,
text=True
)
netstat.stdout.close() # 允许 netstat 正常结束
output = find.communicate()[0]
print(output)
💡 提示:管道操作本质上相当于串联执行多个命令,也可通过多次调用
subprocess.run()实现。
与交互式程序通信
以下示例演示如何通过 subprocess 调用 Python 解释器并执行动态指令:
python
def interactive_program():
"""与交互式程序通信"""
process = subprocess.Popen(
["python", "-i"], # 启动交互式 Python 环境
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
# 发送指令序列
commands = ["print('Hello')", "1 + 1", "exit()"]
for cmd in commands:
process.stdin.write(cmd + "\n")
process.stdin.flush()
# 获取执行结果
output, error = process.communicate()
return output
print(interactive_program())
封装为可复用函数
将常用逻辑封装成函数,可大幅提升代码的可维护性和复用性:
python
import subprocess
from typing import List, Optional, Tuple
def run_command(
cmd: List[str],
cwd: Optional[str] = None,
env: Optional[dict] = None,
timeout: Optional[int] = 30,
check: bool = True
) -> Tuple[int, str, str]:
"""
通用命令执行函数
Args:
cmd: 命令及参数列表
cwd: 工作目录
env: 环境变量
timeout: 超时时间(秒)
check: 是否在非零返回码时抛出异常
Returns:
(returncode, stdout, stderr)
"""
try:
result = subprocess.run(
cmd,
cwd=cwd,
env=env,
capture_output=True,
text=True,
timeout=timeout,
check=check
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired as e:
print(f"命令超时: {' '.join(cmd)}")
return -1, "", f"Timeout after {timeout} seconds"
except subprocess.CalledProcessError as e:
print(f"命令执行失败: {' '.join(cmd)}")
print(f"错误输出: {e.stderr}")
return e.returncode, e.stdout, e.stderr
# 使用示例
returncode, stdout, stderr = run_command(
["docker", "ps", "-a"],
timeout=10
)
好啦,今天的分享就到这里啦,感谢阅读,欢迎三连和关注咧!我们下期再见!🚀