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/")
相关推荐
江沉晚呤时7 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
电脑能手8 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan9 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
老胖闲聊9 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
倔强青铜三9 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三9 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
迷路爸爸18010 小时前
让 VSCode 调试器像 PyCharm 一样显示 Tensor Shape、变量形状、变量长度、维度信息
ide·vscode·python·pycharm·debug·调试
咸鱼鲸11 小时前
【PyTorch】PyTorch中的数据预处理操作
人工智能·pytorch·python
Dxy123931021611 小时前
Python ExcelWriter详解:从基础到高级的完整指南
开发语言·python
金玉满堂@bj11 小时前
Conda 安装包的用途
python