What is the Sh Library
In many Python projects, you need to call shell commands: manage files, run system processes, or interact with installed CLI tools. You can use os.system or subprocess, but they are clunky and require manual handling of arguments, errors, and output.
The Sh library provides a clean, Pythonic way to call shell commands as if they were regular Python functions. It greatly simplifies integrating external utilities, making your code readable and easy to debug.
Benefits of Using Sh
The Sh library offers several key advantages over standard methods for executing system commands:
Readability and Simple Syntax - commands look like regular Python functions, making code more understandable and maintainable.
Automatic Error Handling - the library automatically processes return codes and raises exceptions on errors.
Security - protection against command injection through proper argument escaping.
Flexibility - support for pipelines, background execution, streaming I/O, and many other features.
Installation and Setup
Install the library via pip:
pip install sh
To use it in your code, just one import is needed:
import sh
Core Principles
Sh automatically maps any shell command name to a Python function. This lets you call them naturally:
print(sh.ls("-l"))
Each call returns an object containing stdout, which can be converted to a string, list of lines, bytes, or other formats.
Basic Usage
Working with Files
# List files
print(sh.ls("-lah"))
# Create a file
sh.touch("file.txt")
# Copy a file
sh.cp("file.txt", "copy.txt")
# Delete a file
sh.rm("copy.txt")
# Create a directory
sh.mkdir("test_dir")
# Move a file
sh.mv("file.txt", "test_dir/")
Working with Text
# Display file contents
content = sh.cat("file.txt")
print(str(content))
# Search in files
matches = sh.grep("python", "*.py")
for match in matches:
print(match.strip())
# Count lines
line_count = sh.wc("-l", "file.txt")
print(f"Line count: {line_count.strip()}")
Working with Arguments and Options
Sh supports various ways to pass command arguments:
Positional Arguments
sh.ls("--color", "auto", "/home/user")
Named Arguments
# Long options
sh.ls(color="auto", all=True, human_readable=True)
# Short options
sh.ls(a=True, l=True, h=True)
Combined Approach
# Mixed usage
sh.find("/home", name="*.py", type="f")
Handling Command Output
Getting Output as a String
output = sh.ls()
print(str(output))
Line-by-Line Processing
for line in output:
print(line.strip())
Working with Bytes
raw_output = sh.ls()
bytes_data = raw_output.stdout
Splitting into a List of Lines
lines = str(sh.ls()).split('\n')
for line in lines:
if line.strip():
print(line)
Error Handling
The Sh library provides powerful mechanisms for error handling: