linRichielinRichie
前端
Python
Linux
ChatGPT
  • B 站
  • 500px
前端
Python
Linux
ChatGPT
  • B 站
  • 500px
    • Python学习指南
  • 快速开始

    • Python: 输入与输出 (I/O)
    • Python: 异常处理 try-except
    • Python: List深入概述
    • Python: 面向对象编程(OOP)
  • Python 语法库函数

    • 语法库目录
    • 库

      • library目录
      • argparse:解析命令行参数
      • difflib:比较序列并生成差异信息
      • dnspython: DNS处理库
      • IPy:IP地址处理库
      • logging:记录和管理日志信息
      • os:访问和操作操作系统
      • psutil:系统性能信息库
      • re:正则表达式库
      • smtplib:邮件发送库
    • 函数

      • function目录
      • any() 函数
      • input 函数
      • lambda 和 map 函数
      • reversed()函数
      • zip()函数
    • 语句

      • statement目录
      • import 语句
      • Try/Exception 异常
    • 概念

      • concept目录
      • 深拷贝与浅拷贝
      • 列表、字典与元组
      • 文件读写
      • IO: 输入与输出
      • 逻辑判断与条件语句
      • OOP 面向对象:class
      • OOP: 面向对象编程
  • SQLAlchemy

    • 获取insert或者update的id
  • Pandas

    • Pandas目录
    • Pandas:基础操作
    • Pandas:数据处理与转换
    • Pandas: 数据写入 excel 表格
  • Python前端框架

    • Flask

      • 1. Flask简介
      • 2. Flask程序基本结构
      • 3. Flask请求-响应循环
      • 4. flask案例: 框架网页查询IP
      • Python: Flask中的GitHub OAuth
    • Django

      • chapter-01:Django框架认识

        • 1.1 Django的产生背景
        • 1.2 MTV设计模式
        • 1.3 Django 主要功能模块
      • chapter-02:开发环境配置

        • 2.1 Python的安装与配置
        • 2.2 虚拟环境安装与配置
        • 2.3 Django安装与配置
        • 2.4 MySQL安装配置
      • chapter-03:项目框架搭建

        • 3.1 Django管理工具-创建项目骨架
        • 3.2 修改项目的默认配置
        • 3.3 初始化项目环境
      • chapter-04:ORM应用与原理剖析

        • 4.1 构建POST应用需要的数据集
        • 4.2 Model相关的概念和使用方法
        • 4.3 Model的查询操作API
        • 4.4 ORM实现原理
      • chapter-05:Django管理后台

        • 5.1 将Model注册到管理后台
        • 5.2 管理后台实现原理
      • chapter-06:视图

        • 6.1 视图基础
        • 6.2 视图的高级特性和快捷方法
        • 6.3 基于类的通用视图
      • chapter-07:模板系统

        • 7.1 模板系统基础
        • 7.2 模板语言
      • chapter-08:表单系统

        • 8.2 使用表单系统实现表单: ModelForm
      • chapter-09:用户认证系统

        • 9.1 用户与身份认证
        • 9.2 权限管理
        • 9.3 用户认证系统应用
      • chapter-10:Django路由系统

        • 10.1 路由系统基础
      • chapter-11:Django中间件

        • 11.1 中间件基础
  • Python例子

    • Python: Linux的Shell命令
    • Python: PEP8自动格式化代码
    • Python: pip操作
    • Python: 业务服务监控
    • Python: 从文件逐行读取数据
    • 将链表转换为字符串
    • Python: 检查URL是否能正常访问
    • Python: 爬取网易云音乐
    • Python: 读取目录下的所有内容
    • 案例研究:文本统计
  • Python爬虫

    • 数据解析工具:Xpath
  • 算法题

    • 02:两数相加
    • 09:回文数
    • 13:罗马数值转换为整数
    • 14:最长公共前缀

Python: Linux的Shell命令

  • 简介
  • 执行方法
    • 1. os.system
    • 2. os.popen
    • 3. commands 模块
    • 4. subprocess 模块
    • 5. 异步执行
  • 最佳实践

简介

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())

最佳实践

  1. 选择合适的方法

    • 简单命令用 os.system
    • 需要输出用 subprocess.run
    • 需要实时输出用 Popen
    • 异步场景用 asyncio
  2. 安全考虑

    • 避免直接拼接命令
    • 使用参数列表
    • 注意权限控制
  3. 错误处理

    • 检查返回码
    • 捕获异常
    • 设置超时

注意:

  • 处理命令输出编码
  • 注意错误处理
  • 避免命令注入
  • subprocess 是推荐的现代方法
最近更新时间:
Next
Python: PEP8自动格式化代码