Package: plumbum
Plumbum: Shell CombinatorsEver wished the compactness of shell scripts be put into arealprogramming language?
Say hello toPlumbum Shell Combinators. Plumbum (Latin forlead, which was used to create
pipes back in the day) is a small yet feature-rich library for shell script-like programs in Python.
The motto of the library is“Never write shell scripts again”, and thus it attempts to mimic
theshell syntax(“shell combinators”) where it makes sense, while keeping it allPythonic
and cross-platform.Apart from shell-like syntax and handy shortcuts, the library provides local and remote command
execution (over SSH), local and remote file-system paths, easy working-directory and environment
manipulation, and a programmatic Command-Line Interface (CLI) application toolkit.
Now let’s see some code!This is only a teaser; the full documentation can be found atRead the DocsCheat SheetBasics>>>fromplumbumimportlocal>>>local.cmd.lsLocalCommand(/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 returnsIn the example above, you can uselocal["ls"]if you have an unusually named executable or a full path to an executable. Thelocalobject represents your local machine. As you’ll see, Plumbum also provides remote machines that use the same API!
You can also usefrom plumbum.cmd import lsas well for accessing programs in thePATH.Piping>>>fromplumbum.cmdimportls,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'Redirection>>>fromplumbum.cmdimportcat,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'Working-directory manipulation>>>local.cwd<LocalWorkdir/home/tomer/workspace/plumbum>>>>withlocal.cwd(local.cwd/"docs"):...chain()...'22\n'Foreground and background execution>>>fromplumbumimportFG,BG>>>(ls["-a"]|grep[r"\.py"])&FG# The output is printed to stdout directlybuild.pysetup.pytranslations.py>>>(ls["-a"]|grep[r"\.py"])&BG# The process runs "in the background"<Future['/bin/grep','\\.py'](running)>Command nesting>>>fromplumbum.cmdimportsudo,ifconfig>>>print(sudo[ifconfig["-a"]])/usr/bin/sudo/sbin/ifconfig-a>>>(sudo[ifconfig["-a"]]|grep["-i","loop"])&FGloLinkencap:LocalLoopbackUPLOOPBACKRUNNINGMTU:16436Metric:1Remote commands (over SSH)SupportsopenSSH-compatible clients,PuTTY(on Windows)
andParamiko(a pure-Python implementation of SSH2)>>>fromplumbumimportSshMachine>>>remote=SshMachine("somehost",user="john",keyfile="/path/to/idrsa")>>>r_ls=remote["ls"]>>>withremote.cwd("/lib"):...(r_ls|grep["0.so.0"])()...'libusb-1.0.so.0\nlibusb-1.0.so.0.0.0\n'CLI applicationsimportloggingfromplumbumimportcliclassMyCompiler(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)defset_log_level(self,level):"""Sets the log-level of the logger"""logging.root.setLevel(level)defmain(self,*srcfiles):print("Verbose:",self.verbose)print("Include dirs:",self.include_dirs)print("Compiling:",srcfiles)if__name__=="__main__":MyCompiler.run()Sample output$ 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')Colors and Stylesfromplumbumimportcolorswithcolors.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.")