On this page
  1. shlex
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safely Displaying or Logging Reproducible Shell Commands
  7. 2. Escaping a Single Untrusted Value for POSIX Shells (shlex.quote)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

shlex

Prev: shelve | Up: stdlib_module | Next: shutil
Rel: wave, colorsys, gettext, locale, turtle
Ref: docs.python.org — shlex
Tags: #public #python3 #stdlib


Import

import shlex

Overview

POSIX shell-style lexical tokenizer and safe quoting helper (shlex.split, shlex.join, shlex.quote). Use shlex.split() to parse command strings respecting quotes and escapes, and shlex.join() / shlex.quote() to format copy-pasteable shell commands safely.

Quick Start

import shlex

args = shlex.split('git commit -m "fix: handle spaces & quotes"')
assert args == ["git", "commit", "-m", "fix: handle spaces & quotes"]

cmd = shlex.join(["grep", "-n", "hello world", "my file.txt"])
assert cmd == "grep -n 'hello world' 'my file.txt'"

Implementation Walkthrough

1. Safely Displaying or Logging Reproducible Shell Commands

When running commands via subprocess.run(argv), log them with shlex.join(argv) so users can copy and paste the exact command into their terminal:

import shlex

argv = ["python3", "-m", "pytest", "-k", "test basic & fast"]
print("Running:", shlex.join(argv))

2. Escaping a Single Untrusted Value for POSIX Shells (shlex.quote)

import shlex

raw = "file; echo injected"
assert shlex.quote(raw) == "'file; echo injected'"

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes