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

liftword1周前 (03-05)技术文章4

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 的常用参数执行命令

作为 Python 的初学者,最不缺见的就是命令行工具 python 的执行命令了,每每遇到就可能去查资料帮助,同样,自己也会不时的需要某些执行命令来完成自己的需求,鉴于此我对 python 工具的执...

python中执行shell命令的几个方法小结!很实用,帮助很大

最近有个需求就是页面上执行shell命令,第一想到的就是os.system,os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。...

Python 中的一些命令行命令

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

入门必学25个python常用命令

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

Python 基础教程 九之cron定时执行python脚本

前言在Linux或Unix系统中,你可以使用cron任务来定时执行Python脚本。cron是一个基于时间的作业调度器,允许你安排命令或脚本在系统上自动执行。安装cron大多数Linux发行版默认安装...