如何在 Python 中执行外部命令 ?

liftword3个月前 (03-05)技术文章24

Python 是一种强大的编程语言,可以帮助自动执行许多任务,包括在 Linux 系统上运行命令。在本指南的最后,您将能够使用 Python 轻松有效地执行 Linux 命令。

使用 os 模块

os 模块是 Python 标准库的一部分,它提供了一种使用操作系统相关功能的方法。

运行 Linux 命令的最简单方法之一是使用 os.system 模块。

import os

# Running a simple command
os.system("ls -l")

os.system 易于使用,但不建议用于更复杂的任务,因为它不太灵活,不能直接捕获命令的输出。

使用 subprocess.run

subprocess 模块是 Python 中在运行系统命令更强大的替代方案。它允许您产生新的过程,连接到它们的输入/输出/错误管道,并获取其返回代码。

Python 3.5 引入了 run 函数,这是推荐的方法,因为它更通用。

import subprocess

# Running a command and capturing its output
completed_process = subprocess.run(["ls", "-l"], capture_output=True, text=True)

# Accessing the output
print(completed_process.stdout)

# Checking the return code
if completed_process.returncode != 0:
    print("The command failed with return code", completed_process.returncode)

使用 subprocess.Popen

对于与 subprocesses 更复杂的交互,使用 Popen

import subprocess

# Starting a process
process = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# Communicating with the process
stdout, stderr = process.communicate()

# Printing the output
print(stdout)

# Checking if the process had an error
if process.returncode != 0:
    print("Error:", stderr)

捕获命令输出

如上面的示例所示,捕获命令的输出通常是必不可少的。subprocess.runsubprocess.Popen 方法提供了 stdoutstderr 参数,分别用于捕获命令的标准输出和标准错误。

Handling Shell Pipelines

有时,您可能希望执行带有多个命令的 shell 管道。这可以通过将 shell=True 传递给 subprocess.runsubprocess.Popen 方法。

import subprocess

# Running a shell pipeline
completed_process = subprocess.run(
    "grep 'some_text' some_file.txt | wc -l",
    shell=True,
    capture_output=True,
    text=True
)

# Printing the output
print(completed_process.stdout.strip())

请谨慎使用 shell=True,特别是在使用用户生成的输入时,因为它更容易受到 shell 注入攻击。

错误处理

当从 Python 执行 Linux 命令时,处理潜在的错误非常重要,例如非零退出码或异常。

import subprocess

try:
    completed_process = subprocess.run(["ls", "-l", "/non/existent/directory"], check=True, text=True)
except subprocess.CalledProcessError as e:
    print(f"The command '{e.cmd}' failed with return code {e.returncode}")

我的开源项目

  • course-tencent-cloud(酷瓜云课堂 - gitee 仓库)
  • course-tencent-cloud(酷瓜云课堂 - github 仓库)

相关文章

Python 中的一些命令行命令

虽然 Python 通常用于构建具有图形用户界面 (GUI) 的应用程序,但它也支持命令行交互。命令行界面 (CLI) 是一种基于文本的方法,用于与计算机的操作系统进行交互并运行程序。从命令行运行 P...

入门必学25个python常用命令

以下是 Python 入门必学的 25 个常用命令(函数、语句等):基础输入输出与数据类型print():用于输出数据到控制台,例如print("Hello, World!")。input():获取用...

Python 42个基本命令,开启编程新世界大门

一文带你吃透 Python 42 个基本命令,小白必看!作为一名编程界的 “老司机”,我深知 Python 在编程领域的重要地位。它就像一把万能钥匙,能开启无数扇通往不同应用领域的大门,无论是数据分析...

Python实现轻量级数据库引擎(续)——新增“事务功能”

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。前期基础教程:「Python3.11.0」手把手教你安装最新版Python运行环境讲讲Python环境使用Pip命令快速下载各类库...

python常用命令及操作语句

常用操作脚本1.查看python安装包命令pip3 list2.python 安装封装包命令pip3 install 包名# 例如:pip3 install numpy3.python安装tensor...

python散装笔记——83: 解析命令行参数

大多数命令行工具依赖于程序执行时传递给程序的参数。这些程序不提示输入,而是期望设置数据或特定的标志(变成布尔值)。这使得用户和其他程序都能在 Python 文件启动时通过数据运行它。本节将解释和演示...