Skip to main content

Plumbum: shell combinators library

Project description

Coverage Status PyPI Status Linux and Mac Build Status Windows Build Status Documentation Status

Plumbum: Shell Combinators

Ever wished the compactness of shell scripts be put into a real programming language? Say hello to Plumbum Shell Combinators. Plumbum (Latin for lead, 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 the shell syntax (“shell combinators”) where it makes sense, while keeping it all Pythonic 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 at Read the Docs

Cheat Sheet

Basics

>>> 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

Instead of writing xxx = local["xxx"] for every program you wish to use, you can also import commands

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

Piping

>>> 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'

Redirection

>>> ((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'

Working-directory manipulation

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

Foreground and background execution

>>> 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)>

Command nesting

>>> 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

Remote commands (over SSH)

Supports openSSH-compatible clients, PuTTY (on Windows) and Paramiko (a pure-Python implementation of 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 applications

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()
Sample output
$ 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')

Colors and Styles

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.")
PyPI Versions PyPI License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

plumbum-1.6.3.tar.gz (82.1 kB view details)

Uploaded Source

Built Distributions

plumbum-1.6.3.win32.exe (163.7 kB view details)

Uploaded Source

plumbum-1.6.3-py2.py3-none-any.whl (99.6 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file plumbum-1.6.3.tar.gz.

File metadata

  • Download URL: plumbum-1.6.3.tar.gz
  • Upload date:
  • Size: 82.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for plumbum-1.6.3.tar.gz
Algorithm Hash digest
SHA256 0249e708459f1b05627a7ca8787622c234e4db495a532acbbd1f1f17f28c7320
MD5 e0c588ba9271711fae3beb8c0511e8a9
BLAKE2b-256 5015f26f60e1bb82aabed7ff86f3fd2976784047f9a291c63ac9019086a69559

See more details on using hashes here.

File details

Details for the file plumbum-1.6.3.win32.exe.

File metadata

  • Download URL: plumbum-1.6.3.win32.exe
  • Upload date:
  • Size: 163.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for plumbum-1.6.3.win32.exe
Algorithm Hash digest
SHA256 33442d3cb09c9a4020379bebb17bff9420dad27ad47240427a1512ff26b52d88
MD5 67d686878cfa9679ba544066139748ca
BLAKE2b-256 34753fd25cf00045a92c0db74709149c279eb0ad5913e0c1791f0edde8a1c112

See more details on using hashes here.

File details

Details for the file plumbum-1.6.3-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for plumbum-1.6.3-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 cb467353a070e324afef8666bf488abcabf77a7b221ff87d7a5c62c6beb8c5c4
MD5 0846487a4a1a85194110938e023b3821
BLAKE2b-256 866e2976af0c43f5d6ba2179e1f024a62a886737b0cf46bfff1cc987d55bbcaf

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page