On this page
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
- POSIX shell rules only:
shlex.quote()andshlex.split()target POSIX shells (sh/bash/zsh), NOT Windowscmd.exe(usesubprocess.list2cmdline()on Windows if needed). - Prefer
subprocess.run(argv)without a shell over constructing a quoted shell string withshlex.quote(). - Unclosed quotes raise
ValueError: No closing quotation: CatchValueErrorwhen callingshlex.split()on user-typed input.
Common Functions
- shlex.join() —
join(split_command)— Return a shell-escaped string from split_command. - shlex.quote() —
quote(s)— Return a shell-escaped version of the string s. - shlex.split() —
split(s, comments=False, posix=True)— Split the string s using shell-like syntax.
Classes & Objects
- shlex.shlex — A lexical analyzer class for simple shell-like syntaxes. (Methods:
.error_leader(),.get_token(),.pop_source(),.punctuation_chars(),.push_source(),.push_token())
Linked from
Related notes
- tuts/python3/stdlib_module/shelve Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/shutil Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/cmd links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/colorsys Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/gettext Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/locale Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/shlex/join Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/shlex/quote Linked here; shared tags: #stdlib