Skip to main content

Plumbum:shell 组合器库

项目描述

文件状态 Linux 和 Mac 构建状态 Windows 构建状态 覆盖状态 PyPI 状态 PyPI 版本 Anaconda 服务器徽章 PyPI 许可证 在 https://gitter.im/plumbumpy/Lobby 加入聊天

铅:壳组合器

曾经希望将紧凑的 shell 脚本放入真正的编程语言中吗?向Plumbum Shell Combinators打个招呼。Plumbum(拉丁语中的,在当时被用来创建管道)是一个小型但功能丰富的库,用于 Python 中的类似 shell 脚本的程序。该库的座右铭是“永远不再编写 shell 脚本”,因此它试图在有意义的地方模仿shell 语法(“shell 组合器”),同时保持所有Pythonic 和跨平台

除了类似于 shell 的语法和方便的快捷方式外,该库还提供本地和远程命令执行(通过 SSH)、本地和远程文件系统路径、简单的工作目录和环境操作,以及编程命令行界面 (CLI) 应用程序工具包。现在让我们看一些代码!

这只是一个预告片;完整的文档可以在 阅读文档中找到

备忘单

基本

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

除了为您希望使用的每个程序编写xxx = local["xxx"] 之外,您还可以导入命令

>>> from plumbum.cmd import grep, wc, cat, head
>>> grep
LocalCommand(<LocalPath /bin/grep>)

管道

>>> chain = ls["-a"] | grep["-v", "\\.py"] | wc["-l"]
>>> print chain
/bin/ls -a | /bin/grep -v '\.py' | /usr/bin/wc -l
>>> chain()
u'13\n'

重定向

>>> ((cat < "setup.py") | head["-n", 4])()
u'#!/usr/bin/env python\nimport os\n\ntry:\n'
>>> (ls["-a"] > "file.list")()
u''
>>> (cat["file.list"] | wc["-l"])()
u'17\n'

工作目录操作

>>> local.cwd
<Workdir /home/tomer/workspace/plumbum>
>>> with local.cwd(local.cwd / "docs"):
...     chain()
...
u'15\n'

前台和后台执行

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

命令嵌套

>>> from plumbum.cmd import sudo
>>> print sudo[ifconfig["-a"]]
/usr/bin/sudo /sbin/ifconfig -a
>>> (sudo[ifconfig["-a"]] | grep["-i", "loop"]) & FG
lo        Link encap:Local Loopback
          UP LOOPBACK RUNNING  MTU:16436  Metric:1

远程命令(通过 SSH)

支持与openSSH兼容的客户端、 PuTTY(在 Windows 上)和Paramiko(SSH2 的纯 Python 实现)

>>> 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"])()
...
u'libusb-1.0.so.0\nlibusb-1.0.so.0.0.0\n'

CLI 应用程序

import logging
from plumbum import cli

class MyCompiler(cli.Application):
    verbose = cli.Flag(["-v", "--verbose"], help = "Enable verbose mode")
    include_dirs = cli.SwitchAttr("-I", list = True, help = "Specify include directories")

    @cli.switch("--loglevel", int)
    def set_log_level(self, level):
        """Sets the log-level of the logger"""
        logging.root.setLevel(level)

    def main(self, *srcfiles):
        print "Verbose:", self.verbose
        print "Include dirs:", self.include_dirs
        print "Compiling:", srcfiles

if __name__ == "__main__":
    MyCompiler.run()
样本输出
$ python simple_cli.py -v -I foo/bar -Ispam/eggs x.cpp y.cpp z.cpp
Verbose: True
Include dirs: ['foo/bar', 'spam/eggs']
Compiling: ('x.cpp', 'y.cpp', 'z.cpp')

颜色和样式

from plumbum import colors
with colors.red:
    print("This library provides safe, flexible color access.")
    print(colors.bold | "(and styles in general)", "are easy!")
print("The simple 16 colors or",
      colors.orchid & colors.underline | '256 named colors,',
      colors.rgb(18, 146, 64) | "or full rgb colors",
      'can be used.')
print("Unsafe " + colors.bg.dark_khaki + "color access" + colors.bg.reset + " is available too.")

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

octarine-plumbum-0.0.3.tar.gz (89.5 kB 查看哈希)

已上传 source