all Python 3shlexfunction
shlex.split()
command-line parsing
Splits a string the way a Unix shell does, honouring quotes and escapes: 'a "b c"' gives ['a', 'b c'].
Syntax
shlex.split(s, comments=False, posix=True)
Unlike str.split(), it keeps a quoted argument whole, which makes it the way to turn a command string into a list for subprocess.run without shell=True. The rules are POSIX shell, not Windows: a backslash escapes, so the path C:\Users becomes C:Users. # comments are kept by default (comments=True strips them), and an unclosed quote raises ValueError.
Examples
import shlex
print(shlex.split('cp "my file.txt" backup/')) # → ['cp', 'my file.txt', 'backup/']
print('cp "my file.txt" backup/'.split()) # → ['cp', '"my', 'file.txt"', 'backup/']
import shlex
print(shlex.split(r'dir C:\Users')) # → ['dir', 'C:Users'] — обратная косая черта съедена
print(shlex.split('run # note', comments=True)) # → ['run']
shlex.split('echo "oops') # → ValueError: No closing quotation
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy