目录
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

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

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

PHP教程
1517
276
Java的评论是什么? Java的评论是什么? Aug 12, 2025 am 08:20 AM

评论Incominjavaareignoredbythecompilereranded forexplanation,notes,OrdisablingCode.thereareThreetypes:1)单位linecommentsStartWith // andlastuntiltheEndoftheline; 2)Multi-lineCommentsBebeNWITH/ANDENCOMMENTBEMEMENT/ANDENDWITH/ANDENDWITH/ANDENDWITH/ANDENDWITH/ANDENDWITH/ANDENDWITH/ANDENDWITH/ANDCANSPANMELTIPLICEMENTS; 3)文档

Java开发的最佳IDE:比较评论 Java开发的最佳IDE:比较评论 Aug 12, 2025 pm 02:55 PM

ThebestJavaIDEin2024dependsonyourneeds:1.ChooseIntelliJIDEAforprofessional,enterprise,orfull-stackdevelopmentduetoitssuperiorcodeintelligence,frameworkintegration,andtooling.2.UseEclipseforhighextensibility,legacyprojects,orwhenopen-sourcecustomizati

如何在Java中使用httpclient API 如何在Java中使用httpclient API Aug 12, 2025 pm 02:27 PM

使用JavaHttpClientAPI的核心是创建HttpClient、构建HttpRequest并处理HttpResponse。1.使用HttpClient.newHttpClient()或HttpClient.newBuilder()配置超时、代理等创建客户端;2.使用HttpRequest.newBuilder()设置URI、方法、头和体来构建请求;3.通过client.send()发送同步请求或client.sendAsync()发送异步请求;4.使用BodyHandlers.ofStr

修复:以太网'身份不明网络” 修复:以太网'身份不明网络” Aug 12, 2025 pm 01:53 PM

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh

您将如何在PHP应用程序中实现API版本? 您将如何在PHP应用程序中实现API版本? Aug 14, 2025 pm 11:14 PM

APIversioninginPHPcanbeeffectivelyimplementedusingURL,header,orqueryparameterapproaches,withURLandheaderversioningbeingmostrecommended.1.ForURL-basedversioning,includetheversionintheroute(e.g.,/v1/users)andorganizecontrollersinversioneddirectories,ro

如何比较爪哇的弦 如何比较爪哇的弦 Aug 12, 2025 am 10:00 AM

使用.equals()比较字符串内容,因为==仅比较对象引用而非实际字符;2.进行忽略大小写的比较时使用.equalsIgnoreCase();3.需要按字母顺序排序时使用.compareTo(),忽略大小写则用.compareToIgnoreCase();4.避免对可能为null的字符串调用.equals(),应使用"literal".equals(variable)或Objects.equals(str1,str2)来安全处理null值;总之,始终关注内容比较而非引用,确

Java中的LinkedList是什么? Java中的LinkedList是什么? Aug 12, 2025 pm 12:14 PM

LinkedList在Java中是一个双向链表,实现了List和Deque接口,适用于频繁插入和删除元素的场景,尤其在列表两端操作时效率高,但随机访问性能较差,时间复杂度为O(n),而插入和删除在已知位置时可达到O(1),因此适合用于实现栈、队列或需要动态修改结构的场合,而不适合频繁按索引访问的读密集型操作,最终结论是LinkedList在修改频繁但访问较少时优于ArrayList。

Excel查找并更换不工作 Excel查找并更换不工作 Aug 13, 2025 pm 04:49 PM

checkSearchSettingStingsTike“ matchentirecellcontents”和“ matchcase” byExpandingOptionsInfindReplace,确保“ lookin” insettovaluesand和“ tocorrectScope”中的“ Issettovaluesand”; 2. look forhiddenChindChareChideCharacterSorformattingTingTingTingBycopyBycopyingByingTextDextDirectly

See all articles