### Plumbum: Basic Local Command Execution Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Demonstrates how to create LocalCommand objects from system executables using `local["command_name"]` and `local.cmd.command_name`, and execute them. It shows how to get the command object and its output, including examples with `ls` and `notepad.exe`. ```Python from plumbum import local ls = local["ls"] ls ls() notepad = local["c:\\windows\\notepad.exe"] notepad() from plumbum.cmd import grep, wc, cat, head grep local.cmd.ls local.cmd.ls() ``` -------------------------------- ### Plumbum: Building CLI Applications Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Provides a complete example of building a command-line interface application using `plumbum.cli`. It demonstrates defining flags, switches, and the main execution logic, along with a sample output. ```Python 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() ``` ```Shell $ 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') ``` -------------------------------- ### Plumbum: Command Nesting Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Illustrates how to nest commands, where the output of one command serves as an argument to another, effectively building complex command lines. It shows an example of using `sudo` with `ifconfig`. ```Python from plumbum.cmd import sudo print(sudo[ifconfig["-a"]]) (sudo[ifconfig["-a"]] | grep["-i", "loop"]) & FG ``` -------------------------------- ### Plumbum: Pipelining Commands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Illustrates how to chain multiple local commands together using the `|` operator to create a pipeline, similar to shell piping. It shows how to construct the chain and execute it to get the final output, using `ls`, `grep`, and `wc`. ```Python chain = ls["-a"] | grep["-v", "\\.py"] | wc["-l"] print(chain) chain() ``` -------------------------------- ### Plumbum: Using Colors and Styles Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Shows how to apply colors and text styles to console output using `plumbum.colors` as a context manager or by combining styles. ```Python 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", ``` -------------------------------- ### Running Plumbum CLI Application and Subcommands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst Examples of executing the `geet.py` CLI application, demonstrating how to get general help, help for a specific subcommand (`commit`), and how to invoke a subcommand with its arguments and switches. ```bash $ python3 geet.py --help geet v1.7.2 The l33t version control Usage: geet.py [SWITCHES] [SUBCOMMAND [SWITCHES]] args... Meta-switches: -h, --help Prints this help message and quits -v, --version Prints the program's version and quits Subcommands: commit creates a new commit in the current branch; see 'geet commit --help' for more info push pushes the current local branch to the remote one; see 'geet push --help' for more info $ python3 geet.py commit --help geet commit v1.7.2 creates a new commit in the current branch Usage: geet commit [SWITCHES] Meta-switches: -h, --help Prints this help message and quits -v, --version Prints the program's version and quits Switches: -a automatically add changed files -m VALUE:str sets the commit message; required $ python3 geet.py commit -m "foo" committing... ``` -------------------------------- ### Nesting Plumbum Commands: Sudo Example Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Demonstrates the powerful feature of command nesting in Plumbum, where one command's arguments can be other commands. This example uses `sudo` to execute `ls` with specific flags, showing both the string representation of the nested command and its actual execution and output. ```python from plumbum.cmd import sudo, ls print(sudo[ls["-l", "-a"]]) ``` ```python from plumbum.cmd import sudo, ls print(sudo[ls["-l", "-a"]]()) # Expected output: 'total 22\ndrwxr-xr-x 8 sebulba Administ 4096 May 9 20:46 .\n[...]' ``` -------------------------------- ### Creating and Executing Remote Commands with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This example shows how to create remote command objects by indexing the remote machine object with the command's name or full path. It demonstrates how these remote command objects can then be executed, similar to local commands, to run programs on the remote system. ```python rem["ls"] rem["/usr/local/bin/python3.2"] r_ls = rem["ls"] r_grep = rem["grep"] r_ls() ``` -------------------------------- ### Plumbum Paths: Common Idioms Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Reference for common idioms and operations when working with paths in Plumbum, including construction, iteration, and comparison. ```APIDOC Idiom Description ``local.cwd`` Common way to make paths ``/`` Construct Composition of parts ``//`` Construct Grep for files Sorting Alphabetical Iteration By parts To str Canonical full path Subtraction Relative path ``in`` Check for file in folder ``` -------------------------------- ### Plumbum: Foreground and Background Execution Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Demonstrates how to execute commands in the foreground (`FG`) to print output directly to stdout, or in the background (`BG`) to get a `Future` object for asynchronous execution. ```Python from plumbum import FG, BG (ls["-a"] | grep["\\.py"]) & FG (ls["-a"] | grep["\\.py"]) & BG ``` -------------------------------- ### Example of Plumbum CLI Colored Output Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst This snippet provides an example of how a Plumbum CLI application's help output appears when color customization is applied. It showcases colored program name, version, usage line, and different switch groups, enhancing readability and user experience. ```text SimpleColorCLI.py 1.0.2 Usage: SimpleColorCLI.py [SWITCHES] Meta-switches -h, --help Prints this help message and quits --help-all Print help messages of all subcommands and quit -v, --version Prints the program's version and quits Switches: ``` -------------------------------- ### Plumbum Colors and Styles API Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Documentation for the Plumbum library's color and style utilities, allowing users to apply foreground and background colors, default styles, and text attributes to console output. ```APIDOC Colors API: Usage: You pick colors from fg or bg, also can reset. Main Colors: - black - red - green - yellow - blue - magenta - cyan - white Default Styles: - warn - title - fatal - highlight - info - success Attributes: - bold - dim - underline - italics - reverse - strikeout - hidden ``` -------------------------------- ### Build Command-Line Applications with Plumbum CLI Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This example illustrates how to define a command-line application using `plumbum.cli.Application`. It demonstrates the use of flags (`cli.Flag`), switches (`cli.SwitchAttr`), and custom switch methods to parse command-line arguments and implement application logic. ```python 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() ``` -------------------------------- ### Example Plumbum RemotePath List Output Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst Demonstrates a typical Python list of RemotePath objects, representing remote file system entries, as might be returned by Plumbum operations like listing directory contents on a remote machine. ```python [, < RemotePath /dev/sdb>, , ] ``` -------------------------------- ### Perform File Globbing with Plumbum Paths Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Demonstrates using the `//` operator for globbing files within a directory or its subdirectories. Shows examples for single and nested glob patterns. ```python >>> p // "*.dll" [, ...] >>> p // "*/*.dll" [, ...] >>> local.cwd / "docs" // "*.rst" [, ...] ``` -------------------------------- ### Plumbum CLI: Optional Arguments Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Reference for various optional arguments available in Plumbum's command-line interface, including flags, switches, and validators. ```APIDOC Utility Usage ``Flag`` True or False descriptor ``SwitchAttr`` A value as a descriptor ``CountOf`` Counting version of ``Flag`` ``@switch`` A function that runs when passed ``@autoswitch`` A switch that gets its name from the function decorated ``@validator`` A positional argument validator on main (or use Py3 attributes) ``` -------------------------------- ### Plumbum: I/O Redirection Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Shows how to perform input and output redirection with local commands using `<` for input and `>` for output. It demonstrates redirecting a file's content as input to a command and redirecting a command's output to a file. ```Python ((cat < "setup.py") | head["-n", 4])() (ls["-a"] > "file.list")() (cat["file.list"] | wc["-l"])() ``` -------------------------------- ### Install Plumbum using pip Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/index.rst Installs the Plumbum library using the pip package manager, which handles PEP 518 compatible dependencies. ```Shell pip install plumbum ``` -------------------------------- ### Piping Remote Commands in Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst Demonstrates two ways to pipe remote commands. The first example shows piping between two remote commands, which is less efficient as data is transferred locally. The second example illustrates piping a remote command's output to a local command, which is more efficient as it avoids unnecessary SSH data transfers. ```Python >>> r_ls = rem["ls"] >>> (r_ls | r_grep["b"])() 'bin\nPublic\n' ``` ```Python >>> from plumbum.cmd import grep >>> (r_ls | grep["b"])() 'bin\nPublic\n' ``` -------------------------------- ### Accessing Local Commands with plumbum.local Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Demonstrates how to create `Command` objects for local executables using `local[]` for explicit paths or `local.cmd` for PATH-based lookup, and then execute them like functions. If a full path is not provided, the system's PATH is searched. ```python from plumbum import local ls = local["ls"] # notepad = local["c:\\windows\\notepad.exe"] # ls() # 'README.rst\nplumbum\nsetup.py\ntests\ntodo.txt\n' ls("-a") # '. # .. # .git # .gitignore # .project # .pydevproject # README.rst # [...]' ls = local.cmd.ls # ``` -------------------------------- ### Working with Remote Paths in Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This example demonstrates the usage of RemotePath objects, which represent file-system paths on a remote system. It shows how to construct remote paths, concatenate them, and check file properties like 'is_file()', analogous to local path operations. ```Python >>> p = rem.path("/bin") >>> p / "ls" >>> (p / "ls").is_file() True >>> rem.path("/dev") // "sd*" ``` -------------------------------- ### Managing Remote Working Directory and Environment with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This example illustrates how to inspect and manipulate the remote machine's current working directory (`cwd`) and environment variables (`env`) using Plumbum. It shows how to change the directory using a context manager and access environment variables like PATH, similar to local machine operations. ```python rem.cwd with rem.cwd(rem.cwd / "Desktop"): print(rem.cwd) rem.env["PATH"] rem.which("ls") ``` -------------------------------- ### Plumbum Path Class API Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Detailed API reference for the Plumbum path class, including methods for creation, status checks, composition, iteration, file operations, and permissions. ```APIDOC Plumbum Path Class API: Creation: - local.path(path: str) - local.cwd - local.env.home Properties: - .dirname: The directory name. - .drive: The drive component. - .root: The root directory. - .name: The final path component. - .suffix: The last file extension. - .stem: The final path component without its suffix. Methods for Status Checks: - .exists() -> bool - .is_dir() -> bool - .is_file() -> bool - .is_symlink() -> bool - .stat() -> os.stat_result Methods for Path Manipulation: - .with_suffix(suffix: str, depth: int = 1): Replaces suffixes. - .with_name(name: str): Replaces the entire name. - .preferred_suffix(suffix: str): Adds suffix if none exists. Methods for Directory/File Operations: - .iterdir(): Iterates over directory contents. - .delete(): Deletes file/directory. - .copy(destination: Path, override: bool = False): Copies path. - .move(destination: Path): Moves path. - .symlink(destination: Path): Creates symbolic link. - .link(destination: Path): Creates hard link. - .unlink(): Removes link. - .chmod(mode: int): Changes permissions. - .chown(owner: Optional[str], group: Optional[str], recursive: Optional[bool]): Changes owner/group. Methods for Relative Paths: - .relative_to(source: Path): Computes relative path. Operators: - / (path composition) - [] (path composition) - // (globbing) - - (relative path computation) ``` -------------------------------- ### Plumbum Path Object File System Modification Methods Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Documentation for methods of the Plumbum Path object that modify the file system. Includes comparisons to Python's standard `pathlib` module. ```APIDOC Method: .link(dst) Description: Make a hard link Compare to Pathlib: ✗ Method: .symlink(dst) Description: Make a symlink Compare to Pathlib: .symlink_to Method: .unlink() Description: Unlink a file (delete) Compare to Pathlib: ✓ Method: .delete() Description: Delete file Compare to Pathlib: .unlink Method: .move(dst) Description: Move file Compare to Pathlib: ✗ Method: .rename(newname) Description: Change the file name Compare to Pathlib: ✓ Method: .copy(dst, override=False) Description: Copy a file Compare to Pathlib: ✗ Method: .mkdir() Description: Make a directory Compare to Pathlib: ✓ (+ more args) Method: .open(mode="r") Description: Open a file for reading Compare to Pathlib: ✓ (+ more args) Method: .read(encoding=None) Description: Read a file to text Compare to Pathlib: .read_text Method: .write(data, encoding=None) Description: Write to a file Compare to Pathlib: .write_text Method: .touch() Description: Touch a file Compare to Pathlib: ✓ (+ more args) Method: .chown(owner=None, group=None, recursive=None) Description: Change owner Compare to Pathlib: ✗ Method: .chmod(mode) Description: Change permissions Compare to Pathlib: ✓ ``` -------------------------------- ### Install Plumbum using Conda Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/index.rst Installs the Plumbum library from the conda-forge channel using the Conda package manager. ```Shell conda install -c conda-forge plumbum ``` -------------------------------- ### Handling Command Fallbacks with plumbum.local.get() Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Illustrates the use of `local.get()` to specify multiple potential locations or names for a command. This method attempts each option in order and raises a `CommandNotFound` exception only if none of the specified commands are found. ```python pandoc = local.get('pandoc', '~/AppData/Local/Pandoc/pandoc.exe', '/Program Files/Pandoc/pandoc.exe', '/Program Files (x86)/Pandoc/pandoc.exe') ``` -------------------------------- ### Plumbum Paths: Path Object Properties Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Reference for properties of Plumbum path objects, detailing attributes like name, stem, directory, and user/group IDs, with comparison to Python's pathlib. ```APIDOC Property Description Compare to Pathlib ``.name`` The file name ✓ ``.basename`` DEPRECATED ``.stem`` Name without extension ✓ ``.dirname`` Directory name ✗ ``.root`` The file tree root ✓ ``.drive`` Drive letter (Windows) ✓ ``.suffix`` The suffix ✓ ``.suffixes`` A list of suffixes ✓ ``.uid`` User ID ✗ ``.gid`` Group ID ✗ ``.parts`` Tuple of ``split`` ✓ ``.parents`` The ancestors of the path ✓ ``.parent`` The ancestor of the path ✓ ``` -------------------------------- ### Executing Piped Commands with ParamikoMachine Session Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst Due to limitations with direct piping using ParamikoMachine commands, this example demonstrates a workaround using the machine's '.session()' method. This allows for executing complex commands with pipes as a single string, overcoming 'ChannelFile' or 'I/O operation on closed file' errors. ```Python >>> s = mach.session() >>> s.run("ls | grep b") (0, 'bin\nPublic\n', '') ``` -------------------------------- ### Plumbum CLI: Special Application Member Variables Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Reference for special member variables that can be set in Plumbum applications to customize program name, version, description, and color settings. ```APIDOC Utility Usage ``PROGNAME=`` Custom program name and/or color ``VERSION=`` Custom version ``DESCRIPTION=`` Custom description (or use docstring) ``DESCRIPTION_MORE=`` Custom description with whitespace ``ALLOW_ABREV=True`` Allow argparse style abbreviations ``COLOR_USAGE=`` Custom color for usage statement ``COLOR_USAGE_TITLE=`` Custom color for usage statement's title ``COLOR_GROUPS=`` Colors of groups (dictionary) ``COLOR_GROUP_TITLES=`` Colors of group titles (dictionary) ``` -------------------------------- ### Plumbum CLI: Common Option Parameters Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Reference for common parameters used when defining CLI options in Plumbum, such as help messages, default values, and group assignments. ```APIDOC Option Used in Usage First argument Non-auto The name, or list of names, includes dash(es) Second argument All The validator docstring ``switch``, ``Application`` The help message ``help=`` All The help message ``list=True`` ``switch`` Allow multiple times (passed as list) ``requires=`` All A list of optional arguments to require ``excludes=`` All A list of optional arguments to exclude ``group=`` All The name of a group ``default=`` All The default if not given ``envname=`` ``SwitchAttr`` The name of an environment variable to check ``mandatory=True`` Switches Require this argument to be passed ``` -------------------------------- ### Nesting Remote Commands with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This snippet illustrates the capability of nesting remote commands in Plumbum, similar to local command nesting. It provides examples of executing a command with `sudo` and chaining multiple SSH connections to run a command on a deeply nested remote machine. ```python r_sudo = rem["sudo"] r_ifconfig = rem["ifconfig"] print(r_sudo[r_ifconfig["-a"]]()) ``` ```python from plumbum.cmd import ssh print(ssh["localhost", ssh["localhost", "ls"]]) ssh["localhost", ssh["localhost", "ls"]]() ``` -------------------------------- ### Piping Commands with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This example illustrates how to create command pipelines in Plumbum, mimicking shell piping. It demonstrates chaining `ls`, `grep`, and `wc` commands together using the `|` operator. The `chain` object represents the entire pipeline, which can then be executed to produce a combined result. ```python >>> 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' ``` -------------------------------- ### Redirecting Input/Output with plumbum Commands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Illustrates how to redirect standard input (`<`) and standard output (`>`) for commands. Input can be redirected from `sys.stdin` or a file, and output can be redirected to a file. If a string is provided for redirection, it's treated as a filename. ```python import sys ((grep["world"] < sys.stdin) > "tmp.txt")() # hello # hello world # what has the world become? # foo # Ctrl+D pressed # '' ``` -------------------------------- ### Initializing and Using Plumbum's ParamikoMachine Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This snippet shows how to import and initialize a ParamikoMachine instance for persistent SSH connections. It then demonstrates executing basic remote commands like 'ls' and 'ls -a' through the established connection, highlighting the efficiency gains over spawning new SSH processes for each command. ```Python >>> from plumbum.machines.paramiko_machine import ParamikoMachine >>> rem = ParamikoMachine("192.168.1.143") >>> rem["ls"] RemoteCommand(, ) >>> r_ls = rem["ls"] >>> r_ls() 'bin\nDesktop\nDocuments\nDownloads\nexamples.desktop\nMusic\nPictures\n...' >>> r_ls("-a") '.\n..\n.adobe\n.bash_history\n.bash_logout\n.bashrc\nbin...' ``` -------------------------------- ### Plumbum Path Object Read-Only Methods Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/quickref.rst Documentation for methods of the Plumbum Path object that query information or return new paths without modifying the file system. Includes comparisons to Python's standard `pathlib` module. ```APIDOC Method: .up(count = 1) Description: Go up count directories Compare to Pathlib: ✗ Method: .walk(filter=*, dir_filter=*) Description: Traverse directories Compare to Pathlib: ✗ Method: .as_uri(scheme=None) Description: Universal Resource ID Compare to Pathlib: ✓ Method: .join(part, ...) Description: Put together paths (/) Compare to Pathlib: .joinpath Method: .list() Description: Files in directory Compare to Pathlib: ✗ (shortcut) Method: .iterdir() Description: Fast iterator over dir Compare to Pathlib: ✓ Method: .is_dir() Description: If path is dir Compare to Pathlib: ✓ Method: .isdir() Description: DEPRECATED Compare to Pathlib: Method: .is_file() Description: If is file Compare to Pathlib: ✓ Method: .isfile() Description: DEPRECATED Compare to Pathlib: Method: .is_symlink() Description: If is symlink Compare to Pathlib: ✓ Method: .islink() Description: DEPRECATED Compare to Pathlib: Method: .exists() Description: If file exists Compare to Pathlib: ✓ Method: .stat() Description: Return OS stats Compare to Pathlib: ✓ Method: .with_name(name) Description: Replace filename Compare to Pathlib: ✓ Method: .with_suffix(suffix, depth=1) Description: Replace suffix Compare to Pathlib: ✓ (no depth) Method: .preferred_suffix(suffix) Description: Replace suffix if no suffix Compare to Pathlib: ✗ Method: .glob(pattern) Description: Search for pattern Compare to Pathlib: ✓ Method: .split() Description: Split into directories Compare to Pathlib: .parts Method: .relative_to(source) Description: Relative path (-) Compare to Pathlib: ✓ Method: .resolve(strict=False) Description: Does nothing Compare to Pathlib: ✓ Method: .access(mode = 0) Description: Check access permissions Compare to Pathlib: ✗ ``` -------------------------------- ### Compose Plumbum Paths Using Operators Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Illustrates how to combine path segments using the `/` operator or `[]` (indexing) for path composition. Also shows how to modify the suffix of a path. ```python >>> p / "notepad.exe" >>> (p / "notepad.exe").is_file() True >>> (p / "notepad.exe").with_suffix(".dll") >>> p["notepad.exe"].is_file() True >>> p["..\\some\\path"]["notepad.exe"].with_suffix(".dll") ``` -------------------------------- ### Simple TypedEnv Abstraction Layer Example Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/typed_env.rst This example shows a basic implementation of `TypedEnv` as an abstraction layer, defining a single environment variable for a CI build ID. ```python class CiBuildEnv(TypedEnv): job_id = TypedEnv.Str("BUILD_ID") ``` -------------------------------- ### Apply Colors and Styles to Terminal Output with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This example demonstrates how to use `plumbum.colors` to add various colors and styles to terminal text. It covers using context managers for safe color application, combining styles, and applying both 16-color, 256-named color, and full RGB values. ```python 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.") ``` -------------------------------- ### Open and Read Files Directly with Plumbum Paths Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Illustrates how Plumbum path objects can be used directly with Python's built-in `open()` function, treating them like strings for file operations. ```python >>> with(open(local.cwd / "docs" / "index.rst")) as f: ... print(read(f)) <...output...> ``` -------------------------------- ### Structuring a Root Application for Plumbum Sub-commands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst Provides an example of a root `cli.Application` (`Geet`) designed to manage sub-commands. It illustrates how to handle cases where no sub-command is provided or an unknown command is given, and how to check the `self.nested_command` attribute to determine if a sub-command was invoked. ```Python class Geet(cli.Application): """The l33t version control""" VERSION = "1.7.2" def main(self, *args): if args: print(f"Unknown command {args[0]}") return 1 # error exit code if not self.nested_command: # will be ``None`` if no sub-command follows print("No command given") return 1 # error exit code ``` -------------------------------- ### Plumbum API: `BaseCommand.popen` Method Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Documentation for the `popen` method of `plumbum.commands.base.BaseCommand`. This method executes a command in the background and returns a standard `subprocess.Popen` object, allowing for asynchronous interaction with the process. ```APIDOC plumbum.commands.base.BaseCommand.popen() -> subprocess.Popen Returns: A subprocess.Popen object. ``` -------------------------------- ### Plumbum: Working Directory Manipulation Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Explains how to change the current working directory for command execution using `local.cwd` as a context manager or the `.with_cwd()` method. It demonstrates running commands within a specific directory. ```Python local.cwd with local.cwd(local.cwd / "docs"): chain() ls_in_docs = local.cmd.ls.with_cwd("docs") ls_in_docs() ``` -------------------------------- ### Plumbum: Remote Command Execution over SSH Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst Explains how to execute commands on a remote machine via SSH using `SshMachine`. It covers establishing a connection and running commands, including changing the working directory on the remote host. ```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"])() ``` -------------------------------- ### Importing Local Commands via plumbum.cmd Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Shows a 'magic import' feature where commands can be directly imported from `plumbum.cmd`. This dynamically created module translates `from plumbum.cmd import foo` into `local["foo"]` behind the scenes, supporting underscore-to-hyphen conversion for command names. ```python from plumbum.cmd import grep, cat cat # ``` -------------------------------- ### Check File Status with Plumbum Paths Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Demonstrates how to create a Plumbum path object and use methods like `exists()`, `is_dir()`, and `is_file()` to check the status and type of a file system entry. ```python >>> p = local.path("c:\\windows") >>> p.exists() True >>> p.is_dir() True >>> p.is_file() False ``` -------------------------------- ### Generating HTML Color Table with Custom Style Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/colorlib.rst Shows how to iterate through the htmlcolors factory to generate a list of color examples, displaying the color swatch, hex code, and camel-cased name in HTML format. ```python for color in htmlcolors: htmlcolors.li( "■" | color, color.fg.hex_code | htmlcolors.code, color.fg.name_camelcase) ``` -------------------------------- ### Iterate Over Directory Contents with Plumbum Paths Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/paths.rst Shows how to iterate directly over a Plumbum path object representing a directory to list its immediate contents. Notes that `.iterdir()` might be faster on Python 3.5+. ```python >>> for p2 in p: ... print(p2) ... c:\\windows\\addins c:\\windows\\appcompat c:\\windows\\apppatch ... ``` -------------------------------- ### Command Nesting with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This example demonstrates command nesting, a powerful feature allowing one command to act as an argument or part of another. It shows how to combine `sudo` with `ifconfig` to execute a privileged command. The resulting nested command can then be piped to other commands, such as `grep`, for further processing. ```python >>> 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 ``` -------------------------------- ### Customizing Plumbum CLI Help and Version Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst This example demonstrates how to customize the information displayed by the built-in `help()` and `version()` functions in a Plumbum CLI application. By defining class-level attributes like `PROGNAME` and `VERSION`, developers can control the program name and version shown to users. ```python class MyApp(cli.Application): PROGNAME = "Foobar" VERSION = "7.3" ``` -------------------------------- ### Plumbum: Redirecting Standard I/O with `grep` and `cat` Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Demonstrates how to redirect standard input and output using Plumbum. It shows redirecting `sys.stdin` to `grep` and output to a file, as well as using the `<<` shortcut for direct string input to a command like `cat` piped to `grep`. Note that `grep["world"] < sys.stdin > "tmp.txt"` requires parentheses to avoid chained comparison evaluation. ```Python >>> cat("tmp.txt") 'hello world\nwhat has the world become?\n' ``` ```Python >>> (cat << "hello world\nfoo\nbar\spam" | grep["oo"]) () 'foo\n' ``` -------------------------------- ### Plumbum API: `BaseCommand.run` Method Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Documentation for the `run` method of `plumbum.commands.base.BaseCommand`. This method executes a command and returns a 3-tuple containing the exit code, standard output, and standard error. It supports an optional `retcode` argument for exit code validation. ```APIDOC plumbum.commands.base.BaseCommand.run(retcode: Optional[Union[int, Tuple[int, ...]]] = 0) -> Tuple[int, str, str] retcode: Expected exit code(s). If None, any exit code is accepted. If an int, it must match. If a tuple, any of the values must match. Defaults to 0. Returns: A 3-tuple (exit_code, stdout, stderr). ``` -------------------------------- ### Plumbum CLI Terminal Utilities API Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst API documentation for various terminal utilities available in `plumbum.cli.terminal`, including functions for getting terminal size and methods for user input. ```APIDOC plumbum.cli.terminal: get_terminal_size(default=(80,25)) Returns: tuple (width, height) - cross-platform terminal size. User Input Methods: readline() ask() choose() prompt() ``` -------------------------------- ### Plumbum: Executing Commands with `run` and `popen` Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Details the `run` and `popen` methods for executing commands. `run` returns a 3-tuple (exit code, stdout, stderr) and can accept `retcode` arguments. `popen` executes the command in the background, returning a `subprocess.Popen` object for manual interaction (e.g., `communicate()`, `wait()`, `terminate()`). ```Python >>> ls.run("-a") (0, '.\n..\n.git\n.gitignore\n.project\n.pydevproject\nREADME.rst\nplumbum[...]', '') ``` ```Python >>> p = ls.popen("-a") >>> p.communicate() ('.\n..\n.git\n.gitignore\n.project\n.pydevproject\nREADME.rst\nplumbum\n[...]', '') ``` -------------------------------- ### Access and Set Environment Variables with local.env Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_machine.rst Shows how `local.env` acts as a dictionary-like object to access and modify local environment variables. It demonstrates getting the value of 'JAVA_HOME' and then setting it to a new value, illustrating basic manipulation. ```Python >>> local.env["JAVA_HOME"] 'C:\\Program Files\\Java\\jdk1.6.0_20' >>> local.env["JAVA_HOME"] = "foo" ``` -------------------------------- ### Plumbum: Controlling Process Execution with `FG` and `BG` Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Introduces the `FG` (Foreground) and `BG` (Background) special objects for controlling how commands are executed. `FG` runs programs interactively, inheriting parent's I/O. `BG` runs programs in the background, returning a `Future` object for asynchronous management, similar to `popen` but with a different return type. ```Python >>> from plumbum import FG, BG ``` ```Python >>> ls["-l"] & FG total 5 -rw-r--r-- 1 sebulba Administ 4478 Apr 29 15:02 README.rst drwxr-xr-x 2 sebulba Administ 4096 Apr 27 12:18 plumbum ``` -------------------------------- ### Plumbum: Managing Process Exit Codes and Exceptions Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Explains how Plumbum handles non-zero exit codes by raising `ProcessExecutionError` exceptions. It shows how to suppress these exceptions by setting `retcode=None` or by specifying expected exit codes (single value or tuple). It also introduces the `run` method for retrieving the exit code, stdout, and stderr simultaneously. ```Python >>> cat("non/existing.file") Traceback (most recent call last): [...] ProcessExecutionError: Unexpected exit code: 1 Command line: | /bin/cat non/existing.file Stderr: | /bin/cat: non/existing.file: No such file or directory ``` ```Python >>> cat("non/existing.file", retcode = None) '' ``` ```Python >>> cat("non/existing.file", retcode = 17) Traceback (most recent call last): [...] ProcessExecutionError: Unexpected exit code: 1 Command line: | /bin/cat non/existing.file Stderr: | /bin/cat: non/existing.file: No such file or directory ``` ```Python grep("foo", "myfile.txt", retcode = (0, 2)) ``` ```Python >>> cat["non/existing.file"].run(retcode=None) (1, '', '/bin/cat: non/existing.file: No such file or directory\n') ``` -------------------------------- ### Input and Output Redirection with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This snippet showcases input and output redirection capabilities within Plumbum. It demonstrates redirecting the content of `setup.py` to `cat` and then piping it to `head`. Additionally, it shows how to redirect the output of `ls` to a file and then read from that file using `cat`. ```python >>> 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' ``` -------------------------------- ### Binding Arguments to plumbum Commands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Explains how to bind arguments to a command using square brackets (`__getitem__`). This creates a `BoundCommand` object that 'remembers' its arguments without executing the program immediately. The bound command can then be invoked later. ```python ls["-l"] # BoundCommand(, ('-l',)) grep["-v", ".py"] # BoundCommand(, ('-v', '.py')) ls["-l"]() # Equivalent to ls("-l") ``` -------------------------------- ### Applying Text Colors and Styles with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/_cheatsheet.rst This snippet illustrates how to use the Plumbum library to apply different text colors and styles. It showcases the use of named colors, RGB color definitions, and background colors, highlighting both the safe chaining method and direct (potentially unsafe) access. ```python 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.") ``` -------------------------------- ### Setting up SSH Tunnels with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/remote.rst This snippet demonstrates how to create an SSH tunnel from a local port to a remote port using Plumbum's `tunnel` method. It illustrates both direct tunnel creation with explicit closing and using the tunnel as a context manager for automatic resource cleanup, enabling secure forwarding of network connections. ```python tun = rem.tunnel(6666, 8888) tun.close() ``` ```python with rem.tunnel(6666, 8888): pass ``` -------------------------------- ### Safe Color Manipulation with Plumbum Styles Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/colorlib.rst This example showcases various safe methods for applying colors and styles using `plumbum.colors`. It illustrates using `Style` objects as context managers for automatic restoration, wrapping strings with `color.wrap()` or `color[]` for styled output, and direct printing with `color.print()`. The snippet also demonstrates combining multiple styles using the `&` operator and nesting context managers. ```python colors.fg.yellow('This is yellow', end='') print(' And this is normal again.') with colors.red: print('Red color!') with colors.bold: print("This is red and bold.") print("Not bold, but still red.") print("Not red color or bold.") print((colors.magenta & colors.bold)["This is bold and colorful!"], "And this is not.") ``` -------------------------------- ### Configure Plumbum Switches with Environment Variables Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst This example shows how to link a `SwitchAttr` to an environment variable using the `envname` parameter. If the environment variable is set, its value will be used for the switch, unless overridden by a command-line argument. This allows for flexible configuration. ```python class MyApp(cli.Application): log_file = cli.SwitchAttr("--log-file", str, envname="MY_LOG_FILE") def main(self): print(self.log_file) ``` ```bash $ MY_LOG_FILE=this.log ./example.py this.log ``` -------------------------------- ### Pipelining Commands with plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Demonstrates how to form command pipelines using the bitwise-or operator (`|`) with `BoundCommand` objects. This allows chaining multiple commands where the output of one becomes the input of the next, similar to shell pipes. Note that only stderr of the last command is captured by default. ```python chain = ls["-l"] | grep[".py"] print(chain) # C:\Program Files\Git\bin\ls.exe -l | C:\Program Files\Git\bin\grep.exe .py chain() # '-rw-r--r-- 1 sebulba Administ 0 Apr 27 11:54 setup.py\n' # Discarding stderr for intermediate commands chain = (bwa["mem", ...] >= "/dev/null") | samtools["view", ...] ``` -------------------------------- ### Basic Command Execution with Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This snippet demonstrates basic command execution using Plumbum's `local` object. It shows how to access system commands like `ls` and `notepad.exe` and execute them, returning their output or controlling external applications. The `local` object represents the current machine, allowing easy interaction with its command-line utilities. ```python >>> 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 ``` -------------------------------- ### Redirect Output for Plumbum NOHUP Commands Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Explains how to customize the output redirection for commands run with the `NOHUP` modifier. It shows how to direct standard output to a specific file path or suppress it entirely by setting `stdout` to `/dev/null` or `None`. ```python >>> ls["-a"] & NOHUP(stdout='/dev/null') # Or None ``` -------------------------------- ### Plumbum CLI Application Class Reference Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/cli.rst This section provides API documentation for the `plumbum.cli.Application` class, which serves as the foundation for Plumbum CLI programs. It details the essential `main()` method for application logic, the `run()` classmethod for execution, and the default `help()` and `version()` switches. ```APIDOC plumbum.cli.Application: Description: The base class for building command-line applications. Methods: main(args...): Description: The core method to implement your application's logic. Receives remaining positional arguments after switches are processed. run(): Type: classmethod Description: The entry-point for the application. It instantiates the class, parses arguments, invokes switch functions, and then calls `main()`. Built-in Switches: -h, --help: Description: Displays the help message and quits the application. --version: Description: Displays the program's version and quits the application. Customizable Class Attributes: PROGNAME: string Description: The name of the program displayed in help messages. Can be a colored string. VERSION: string Description: The version of the program displayed. Can be a colored string. DESCRIPTION: string Description: A description of the program. Can be a colored string. COLOR_USAGE: string Description: Color for the usage string. COLOR_USAGE_TITLE: string Description: Color for the 'Usage:' line title. COLOR_GROUPS: dict Description: Dictionary mapping switch group names to colors. COLOR_GROUP_TITLES: dict Description: Dictionary mapping switch group titles to colors. ``` -------------------------------- ### Working Directory Manipulation in Plumbum Source: https://github.com/tomerfiliba/plumbum/blob/master/README.rst This example demonstrates how to inspect and manipulate the current working directory using Plumbum's `local.cwd`. It shows how to retrieve the current directory and, more importantly, how to temporarily change the working directory using a `with` statement. This ensures that commands executed within the block operate relative to the specified path. ```python >>> local.cwd >>> with local.cwd(local.cwd / "docs"): ... chain() ... '22\n' ``` -------------------------------- ### Execute Plumbum Commands in Background (BG Modifier) Source: https://github.com/tomerfiliba/plumbum/blob/master/docs/local_commands.rst Demonstrates how to run a command asynchronously using Plumbum's `BG` modifier. It shows how to obtain a `Future` object, check its status, wait for completion, and retrieve the standard output of the background process. ```python >>> ls["-a"] & BG >>> f = _ >>> f.ready() False >>> f.wait() >>> f.stdout '.\n..\n.git\n.gitignore\n.project\n.pydevproject\nREADME.rst\nplumbum\n[...]' ```