shlex.split Parses Shell Style Arguments
shlex.split applies POSIX shell quoting rules to a command string, so quoted spaces, literal hashes and escapes arrive as one argv list ready for subprocess.
Code
import shlex
# shlex.split 按 POSIX shell 规则切分:引号内的空格保留,引号本身剥掉
cmd = 'deploy --env "production eu" --tags web,api --dry-run'
print(shlex.split(cmd))
# 单引号是纯字面量:# 与反斜杠都不特殊
print(shlex.split("--msg 'keep # hash'"))
# Windows 风格路径用 r 前缀写进单引号:反斜杠原样保留
raw_cmd = r"backup --label 'C:\temp' --quiet"
print(shlex.split(raw_cmd))
# 拿到的就是 argv 列表:能直接交给 subprocess 或自己的参数解析
args = shlex.split('render --width 1920 --height 1080')
print(len(args), args[0], int(args[2]))How the snippet works
Module-level bindings hold the data — cmd, raw_cmd, args — with no function scope in between.
Watch out for
- Requires
shlexas a package; the snippet will not run without it.
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `cmd`, `raw_cmd`, `args`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.