基于 plumbum 跨平台执行Shell脚本

Plumbum将系统命令包装成Python对象,是一款Shell组合器。

语法简洁:相比subprocess大幅减少代码量,例如ls["-l", "/tmp"]()替代复杂的subprocess.run调用。

类型安全:参数传递时自动校验类型,避免Shell注入(如文件名包含分号时自动转义)。

功能完备:支持管道、后台执行、环境变量设置、超时控制等高级特性。

跨平台兼容:通过plumbum.machines模块支持本地/远程命令执行(需配合Paramiko)。

安装

shell 复制代码
pip install plumbum

本地命令

python 复制代码
from plumbum import local

git = local['git']
print(git)
print(git('--version'))

# D:\Program Files\Git\cmd\git.exe
# git version 2.27.0.windows.1

管道

python 复制代码
>>> from plumbum.cmd import ls, grep, wc
>>> chain = ls["-a"] | grep["-v", r"\.py"] | wc["-l"]
>>> print(chain)
/bin/ls -a | /bin/grep -v '\.py' | /usr/bin/wc -l
>>> chain()
'27\n'

前后台执行

powershell 复制代码
>>> from plumbum import FG, BG
>>> (ls["-a"] | grep[r"\.py"]) & FG         # The output is printed to stdout directly
build.py
setup.py
translations.py
>>> (ls["-a"] | grep[r"\.py"]) & BG         # The process runs "in the background"
<Future ['/bin/grep', '\\.py'] (running)>

SSH 远程执行

powershell 复制代码
>>> from plumbum import SshMachine
>>> remote = SshMachine("somehost", user = "john", keyfile = "/path/to/idrsa")
>>> r_ls = remote["ls"]
>>> with remote.cwd("/lib"):
...     (r_ls | grep["0.so.0"])()
...
'libusb-1.0.so.0\nlibusb-1.0.so.0.0.0\n'

相关链接

https://github.com/tomerfiliba/plumbum

相关推荐
Lyn_Li32 分钟前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸5 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学6 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python