Python 操作 Linux 命令行

二、基础用法示例

1. 执行简单命令(无输出捕获)

python 复制代码
# 执行 ls -l 命令
subprocess.run(["ls", "-l"])

# 使用 shell=True(注意安全风险)
subprocess.run("ls -l | grep .txt", shell=True)

2. 捕获命令输出

python 复制代码
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print("输出内容:", result.stdout)
print("错误信息:", result.stderr)
print("返回码:", result.returncode)

3. 执行命令并检查错误

python 复制代码
try:
    subprocess.run(["invalid_command"], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
    print(f"命令执行失败: {e}")

三、进阶操作示例

1. 管道操作(|

python 复制代码
# 实现 ls -l | grep .py
p1 = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", ".py"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
output = p2.communicate()[0]
print(output.decode())

2. 输入重定向(<

python 复制代码
# 等价于 grep "hello" < input.txt
with open("input.txt", "r") as f:
    result = subprocess.run(["grep", "hello"], stdin=f, text=True, capture_output=True)
print(result.stdout)

3. 输出重定向(>

python 复制代码
# 等价于 ls -l > output.txt
with open("output.txt", "w") as f:
    subprocess.run(["ls", "-l"], stdout=f)

四、实用场景示例

1. 系统信息获取

python 复制代码
# 获取内核版本
uname_result = subprocess.run(["uname", "-r"], capture_output=True, text=True)
print("内核版本:", uname_result.stdout.strip())

# 获取磁盘使用情况
df_result = subprocess.run(["df", "-h"], capture_output=True, text=True)
print(df_result.stdout)

2. 文件操作

python 复制代码
# 创建目录
subprocess.run(["mkdir", "-p", "test_dir"])

# 递归复制目录
subprocess.run(["cp", "-r", "src_dir", "dest_dir"])

# 压缩文件
subprocess.run(["tar", "-czvf", "archive.tar.gz", "target_dir"])

3. 软件包管理

python 复制代码
# 更新软件包列表(Ubuntu)
subprocess.run(["sudo", "apt", "update"])

# 安装软件
subprocess.run(["sudo", "apt", "install", "nginx", "-y"])

4. 后台进程

python 复制代码
# 启动后台进程(不会阻塞Python脚本)
subprocess.Popen(["python3", "long_running_script.py"])

五、高级技巧

1. 环境变量控制

python 复制代码
# 添加自定义环境变量
env = {"CUSTOM_ENV": "123"}
subprocess.run(["env"], env=env, capture_output=True, text=True)

2. 超时控制

python 复制代码
try:
    subprocess.run(["sleep", "10"], timeout=5)
except subprocess.TimeoutExpired:
    print("命令执行超时!")

3. 交互式命令(如 sudo)

python 复制代码
# 通过 stdin 输入密码(需要配置免密 sudo 更安全)
password = "your_password\n"
result = subprocess.run(
    ["sudo", "-S", "apt", "update"],
    input=password, 
    text=True, 
    capture_output=True
)
print(result.stdout)

六、安全注意事项

  1. 避免 shell=True :除非必要,否则不要使用 shell=True,可能引发命令注入漏洞
  2. 输入校验:所有外部输入需经过严格过滤
  3. 错误处理 :始终检查 returncodestderr

七、完整实战示例

python 复制代码
import subprocess

def system_info():
    # 获取系统信息
    print("=== 系统信息 ===")
    subprocess.run(["uptime"])
    subprocess.run(["free", "-h"])

def backup_directory(src, dest):
    # 目录备份
    print(f"正在备份 {src} 到 {dest}")
    subprocess.run(["rsync", "-avz", src, dest])

if __name__ == "__main__":
    system_info()
    backup_directory("/home/user/docs", "/backup/")
相关推荐
郭庆汝4 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变7 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络8 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find9 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取10 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector12 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习12 小时前
Python入门Day2
开发语言·python
Vertira12 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉12 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗12 小时前
黑马python(二十四)
开发语言·python