基于 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

相关推荐
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama