Github: https://github.com/tomerfiliba/plumbum
プルンバム:シェルコンビネータ
シェルスクリプトのコンパクトさを本当のプログラミング言語にしたいと思ったことはありますか? Plumbum Shell Combinatorsにお立ち寄りください 。 Plumbum(日中にパイプを作成するために使用された鉛のラテン語)は、Pythonのシェルスクリプトのようなプログラムのための、機能が豊富で小さいライブラリです。 ライブラリのモットーは、 “シェルスクリプトをもう一度書いてはいけません”です 。したがって、 Pythonとクロスプラットフォームのすべてを保ちながら、 シェル構文 ( シェル結合子)を模倣しようとします 。
シェルと同様のシンタックスや便利なショートカットとは別に、ローカルとリモートのコマンド実行(SSH経由)、ローカルとリモートのファイルシステムパス、簡単な作業ディレクトリと環境操作、プログラムによるCommand-Line Interface(CLI)アプリケーションツールキット。 さて、いくつかのコードを見てみましょう!
これは単にティーザーです。 完全なドキュメント はDocsの読ん で見つけることができます
カンニングペーパー
基本
>>> 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"]
を書く代わりに、コマンドをimport
することもできます
>>> 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 (純粋なPythonのSSH2実装)をサポートしています。
>>> 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.")