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

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
。
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. 实时输出命令执行过程(不等待完成)
如果你希望看到命令实时输出(比如长时间运行的脚本):

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中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

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

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

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

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

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

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

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

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

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

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

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

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