Python Glossary Русский

Python 3.3+shlexfunction

shlex.quote()

command-line parsing

Escapes a string so it can be safely inserted into a Unix shell command: "it's" becomes 'it'"'"'s'.

Syntax

shlex.quote(s)

It is needed only when a command really must be built as a string for shell=True; a list of arguments without a shell is safer and needs no escaping. The escaping targets POSIX shells: in cmd.exe and PowerShell on Windows it does not prevent injection. An empty string becomes '' so that the argument does not vanish.

Examples

import shlex
name = 'x; rm -rf ~'
print('ls ' + shlex.quote(name))  # → ls 'x; rm -rf ~'
print(shlex.quote(''))  # → ''
print(shlex.quote('safe_name.txt'))  # → safe_name.txt — без кавычек, раз они не нужны

See also

Open in the full glossarydocs.python.orgReport an inaccuracy