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/")
相关推荐
阿福不是狗2 小时前
Python使用总结之Mac安装docker并配置wechaty
python·macos·docker
gen_2 小时前
mac环境下的python、pycharm和pip安装使用
python·macos·pycharm
AI视觉网奇2 小时前
pycharm 左右箭头 最近编辑
ide·python·pycharm
思绪无限3 小时前
Pycharm的终端无法使用Anaconda命令行问题详细解决教程
ide·python·pycharm·终端·命令行·anaconda·问题教程
漫步云端-r3 小时前
Pycharm的使用技巧总结
ide·python·pycharm
风逸hhh4 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮4 小时前
Python训练第四十三天
开发语言·python
互联网杂货铺5 小时前
完美搭建appium自动化环境
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
Gyoku Mint6 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
莱茵菜苗6 小时前
Python打卡训练营day46——2025.06.06
开发语言·python