Python: Linux的Shell命令
2025-02-17
简介
Python 提供了多种方式来执行 Linux Shell 命令。每种方法都有其特点和适用场景。
执行方法
1. os.system
最简单的方式,但功能有限:
import os
# 执行命令
exit_code = os.system('echo "Hello World"')
# 检查返回值
if exit_code == 0:
print("命令执行成功")
else:
print(f"命令执行失败: {exit_code}")2. os.popen
可以获取命令输出:
import os
# 执行命令并获取输出
with os.popen('ls -l') as p:
output = p.read()
print(output)
# 逐行读取输出
with os.popen('ls -l') as p:
for line in p:
print(line.strip())3. commands 模块
提供了更简单的命令执行接口:
import commands
# 获取状态和输出
status, output = commands.getstatusoutput('ls -l')
print(f"状态: {status}")
print(f"输出: {output}")
# 只获取输出
output = commands.getoutput('ls -l')
print(output)
# 获取命令状态
status = commands.getstatus('ls -l')
print(status)4. subprocess 模块
推荐使用的现代方法:
基本用法
import subprocess
# 使用 call
exit_code = subprocess.call(['ls', '-l'])
print(f"退出码: {exit_code}")
# 使用 run (推荐)
result = subprocess.run(['ls', '-l'],
capture_output=True,
text=True)
# 检查结果
if result.returncode == 0:
print("输出:", result.stdout)
else:
print("错误:", result.stderr)Popen 类
# 实时获取输出
process = subprocess.Popen(
'tail -f /var/log/syslog',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
# 读取输出
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
# 等待进程结束
rc = process.poll()5. 异步执行
import asyncio
async def run_command(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
return stdout, stderr
async def main():
stdout, stderr = await run_command('ls -l')
print(stdout.decode())最佳实践
选择合适的方法
- 简单命令用 os.system
- 需要输出用 subprocess.run
- 需要实时输出用 Popen
- 异步场景用 asyncio
安全考虑
- 避免直接拼接命令
- 使用参数列表
- 注意权限控制
错误处理
- 检查返回码
- 捕获异常
- 设置超时
注意:
- 处理命令输出编码
- 注意错误处理
- 避免命令注入
- subprocess 是推荐的现代方法