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'