目录
1. 使用 subprocess.run()(推荐方式)
2. 运行带 shell 特性的命令(使用 shell=True
3. 实时输出命令执行过程(不等待完成)
4. 执行命令并获取返回值判断是否成功
5. 快速执行并获取输出(适合简单场景)
常见用途示例
首页 后端开发 Python教程 python run shell命令示例

python run shell命令示例

Jul 26, 2025 am 07:50 AM
php java 编程

使用 subprocess.run() 可安全执行 shell 命令并捕获输出,推荐以列表传参避免注入风险;2. 需要 shell 特性时可设 shell=True,但需警惕命令注入;3. 使用 subprocess.Popen 可实现实时输出处理;4. 设置 check=True 可在命令失败时抛出异常;5. 简单场景可直接链式调用获取输出;日常应优先使用 subprocess.run(),避免使用 os.system() 或已弃用模块,以上方法覆盖了 Python 中执行 shell 命令的核心用法。

python run shell command example

在 Python 中执行 shell 命令有多种方式,最常用的是使用 subprocess 模块。下面是一些实用的例子,展示如何在 Python 中运行 shell 命令。

python run shell command example

1. 使用 subprocess.run()(推荐方式)

这是 Python 3.5 推荐的方法,简单、安全且功能强大。

import subprocess

# 运行一个简单的 shell 命令
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

# 输出命令的返回码、标准输出和错误
print("返回码:", result.returncode)
print("输出:\n", result.stdout)
print("错误:\n", result.stderr)

? 注意:['ls', '-l'] 是以列表形式传参,避免 shell 注入风险。如果需要 shell 特性(如通配符、管道),加 shell=True

python run shell command example

2. 运行带 shell 特性的命令(使用 shell=True

import subprocess

result = subprocess.run('echo $HOME | xargs ls', shell=True, capture_output=True, text=True)
print("输出:\n", result.stdout)

⚠️ 警告:使用 shell=True 时要小心用户输入,防止命令注入。


3. 实时输出命令执行过程(不等待完成)

如果你希望看到命令实时输出(比如长时间运行的脚本):

python run shell command example
import subprocess

# 实时打印输出
process = subprocess.Popen(['ping', '-c', '5', 'google.com'], stdout=subprocess.PIPE, text=True)

for line in process.stdout:
    print("输出:", line.strip())

process.wait()  # 等待完成
print("完成,返回码:", process.returncode)

4. 执行命令并获取返回值判断是否成功

import subprocess

try:
    subprocess.run(['python', '--version'], check=True, capture_output=True, text=True)
    print("命令执行成功")
except subprocess.CalledProcessError as e:
    print("命令执行失败:", e)
  • check=True 会在命令返回非零状态时抛出异常。

5. 快速执行并获取输出(适合简单场景)

如果你只是想快速获取命令输出,可以用:

import subprocess

# 简洁写法
output = subprocess.run('date', shell=True, capture_output=True, text=True).stdout.strip()
print("当前时间:", output)

常见用途示例

  • 检查文件是否存在:

    result = subprocess.run(['test', '-f', 'config.txt'], capture_output=True)
    if result.returncode == 0:
        print("文件存在")
  • 执行 Git 命令:

    result = subprocess.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], capture_output=True, text=True)
    print("当前分支:", result.stdout.strip())

    基本上就这些常用方式。日常推荐优先使用 subprocess.run(),避免使用已弃用的 os.system()commands 模块。

    以上是python run shell命令示例的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Stock Market GPT

Stock Market GPT

人工智能驱动投资研究,做出更明智的决策

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

如何在Java中使用柜台使用循环? 如何在Java中使用柜台使用循环? Sep 30, 2025 am 11:24 AM

AforloopinjavausesacountertorepeatCode:initialize(例如,Inti = 0),setCondition(例如,i

什么是特征以及如何在PHP中使用它们 什么是特征以及如何在PHP中使用它们 Oct 02, 2025 am 04:17 AM

特质sinphpenablehorizo​​ntalcodereusebyAllowingClassobalingMethodMethodSsobabableTraitContainers,旁路lephingsingleinheritancelimits.forexample,theloggabletraitprovidesalog(theloggabletraitprovidesalog)()methodyClassusisitit,suptoyclassusisitit,shisthencuser,shisthencuser,shisthencallencall $ the canthencall $ thiscrigthiscrea thiscreacreacrea

如何在Java中实现阻塞队列 如何在Java中实现阻塞队列 Oct 01, 2025 am 02:57 AM

使用Java内置的BlockingQueue接口是实现阻塞队列的推荐方式,如ArrayBlockingQueue提供基于数组的有界线程安全队列;2.可通过synchronized、wait()和notifyAll()从零构建自定义阻塞队列,确保在队列满时put方法阻塞、队列空时take方法阻塞,并使用while循环防止虚假唤醒;3.内置实现线程安全、性能优越且支持超时操作,应优先用于生产环境,自定义实现主要用于学习或特殊需求。

如何将文件类用于Java中的现代文件操作 如何将文件类用于Java中的现代文件操作 Oct 04, 2025 am 12:03 AM

TheFilesclassinJavaprovidesamodernAPIforfileoperations.Itsimplifiesreading,writing,copying,moving,anddeletingfilesusingstaticmethodslikereadAllLines,write,copy,move,anddelete.UsePaths.get()tocreatePathobjects,andapplyFilesmethodsforefficient,readable

如何使用set_error_handler在PHP中创建自定义错误处理程序 如何使用set_error_handler在PHP中创建自定义错误处理程序 Oct 02, 2025 am 03:54 AM

set_error_handlerinPHPenablescustomerrorhandlingbydefiningafunctionthatinterceptsrecoverableerrors,allowingcontrolledlogginganduser-friendlyresponses;itacceptsparameterslike$errno,$errstr,$errfile,and$errlinetocaptureerrordetails,isregisteredviaset_e

Debotnet:一款针对Windows10隐私设置和数据的保护工具 Debotnet:一款针对Windows10隐私设置和数据的保护工具 Sep 29, 2025 am 10:15 AM

DebotnetDebotnet是一款针对Windows10隐私设置和数据的保护工具,Debotnet本质上是一个免费的可移植工具,它可以帮助我们控制和管理Windows10中跟隐私相关的配置,并保证用户的个人数据安全性。实际上,如果你想要保护你的隐私数据时,你就会发现Windows10的默认隐私设置还是有很多可以改进的地方。每当我们在为家庭或工作环境设置新的电脑或更新当前设置时,我们总是需要花时间去仔细检查安装配置过程中的每一个隐私设置,并尽可能地确保我们的隐私信息得到最好的安全保护。在保护用

修复大声笑防火墙阻止游戏连接问题 修复大声笑防火墙阻止游戏连接问题 Oct 05, 2025 am 06:34 AM

IfLeagueofLegendscan'tconnectduetofirewallissues,trythesesteps:1.AllowLeagueClient.exethroughWindowsFirewall.2.RepairorreinstallRiotClientservices.3.Createcustominbound/outboundfirewallrules.4.Temporarilydisablethird-partyantivirusfirewallstotestconn

如何在Java中生成安全的随机密码? 如何在Java中生成安全的随机密码? Oct 04, 2025 am 04:11 AM

使用SecureRandom生成安全密码,结合大小写字母、数字和特殊字符,确保密码多样性并避免使用不安全的随机数生成器。

See all articles