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.

PythonCli Tooling

Code

pythonsnippet
16 lines
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 shlex as a package; the snippet will not run without it.

Interactive Tools for This Topic

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`.