Plumbum:shell组合库
项目描述
Plumbum:Shell组合
是否曾希望将shell脚本的紧凑性融入真正的编程语言中?现在向您介绍 Plumbum Shell Combinators。Plumbum(拉丁语意为铅,昔日用于创建管道)是一个小巧但功能丰富的Python库,用于编写类似shell的程序。该库的座右铭是“永不再次编写shell脚本”,因此它试图在合理的地方模仿shell语法(“shell组合器”),同时保持其Python化和跨平台。
除了类似shell的语法和便捷的快捷方式外,该库还提供本地和远程命令执行(通过SSH)、本地和远程文件系统路径、轻松的工作目录和环境操作,以及程序化命令行界面(CLI)应用程序工具包。现在让我们看看一些代码!
这只是一个预告;完整文档可以在 Read the Docs 找到。
速查表
基础
>>> from plumbum import local
>>> local.cmd.ls
LocalCommand(/bin/ls)
>>> local.cmd.ls()
'build.py\nCHANGELOG.rst\nconda.recipe\nCONTRIBUTING.rst\ndocs\nexamples\nexperiments\nLICENSE\nMANIFEST.in\nPipfile\nplumbum\nplumbum.egg-info\npytest.ini\nREADME.rst\nsetup.cfg\nsetup.py\ntests\ntranslations.py\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
''                                              # Notepad window is closed by user, command returns在上面的示例中,如果您有一个不寻常命名的可执行文件或可执行文件的完整路径,可以使用local["ls"]。local对象代表您的本地计算机。您将看到,Plumbum还提供了使用相同API的远程计算机!您还可以使用from plumbum.cmd import ls来访问PATH中的程序。
管道
>>> 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'重定向
>>> from plumbum.cmd import cat, head
>>> ((cat < "setup.py") | head["-n", 4])()
'#!/usr/bin/env python3\nimport os\n\ntry:\n'
>>> (ls["-a"] > "file.list")()
''
>>> (cat["file.list"] | wc["-l"])()
'31\n'工作目录操作
>>> local.cwd
<LocalWorkdir /home/tomer/workspace/plumbum>
>>> with local.cwd(local.cwd / "docs"):
...     chain()
...
'22\n'前台和后台执行
>>> 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)>命令嵌套
>>> from plumbum.cmd import sudo, ifconfig
>>> 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"])()
...
'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()示例输出
$ python3 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.")项目详情
下载文件
下载适用于您平台的自定义文件。如果您不确定选择哪个,请了解有关安装软件包的更多信息。
源分布
         plumbum-1.8.3.tar.gz (318.9 kB 查看哈希值)
      
    构建分布
         plumbum-1.8.3-py3-none-any.whl (127.6 kB 查看哈希值)
      
    
    
       关闭
    
      
        
    
    
  
plumbum-1.8.3.tar.gz的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 6092c85ab970b7a7a9d5d85c75200bc93be82b33c9bdf640ffa87d2d7c8709f0 | |
| MD5 | 02ac5ff47e1a20105b24e9f9b6be3b8e | |
| BLAKE2b-256 | 236206260ec9f1f5a8c04418f8c8c7c2877c80cac4ead97224fc14d92f0db6b4 | 
    
       关闭
    
      
        
    
    
  
plumbum-1.8.3-py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 8595d36dae2472587d6f59789c8d7b26250f45f6f6ed75ccb378de59ee7b9cf9 | |
| MD5 | 91c2e8f880b589fc8cc8661392190d1b | |
| BLAKE2b-256 | fa0853cf4fb6bebdfd2598e9d620a587229c3bfcc8df1a202289da07e5b282cd |