mirror of
https://github.com/python/cpython.git
synced 2025-08-30 13:38:43 +00:00
Add shlex.quote function, to escape filenames and command lines (#9723).
This function used to live as pipes.quote, where it was undocumented but used anyway. (An alias still exists for backward compatibility.) The tests have been moved as is, but the code of the function was changed to use a regex instead of a loop with string comparisons (at Ian Bicking’s suggestion). I’m terrible at regexes, so any feedback is welcome.
This commit is contained in:
parent
fcdaaa9011
commit
9bce311ea4
7 changed files with 66 additions and 42 deletions
23
Lib/pipes.py
23
Lib/pipes.py
|
@ -62,7 +62,9 @@ For an example, see the function test() at the end of the file.
|
|||
import re
|
||||
import os
|
||||
import tempfile
|
||||
import string
|
||||
# we import the quote function rather than the module for backward compat
|
||||
# (quote used to be an undocumented but used function in pipes)
|
||||
from shlex import quote
|
||||
|
||||
__all__ = ["Template"]
|
||||
|
||||
|
@ -245,22 +247,3 @@ def makepipeline(infile, steps, outfile):
|
|||
cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd
|
||||
#
|
||||
return cmdlist
|
||||
|
||||
|
||||
# Reliably quote a string as a single argument for /bin/sh
|
||||
|
||||
# Safe unquoted
|
||||
_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+=:,./')
|
||||
|
||||
def quote(file):
|
||||
"""Return a shell-escaped version of the file string."""
|
||||
for c in file:
|
||||
if c not in _safechars:
|
||||
break
|
||||
else:
|
||||
if not file:
|
||||
return "''"
|
||||
return file
|
||||
# use single quotes, and put single quotes into double quotes
|
||||
# the string $'b is then quoted as '$'"'"'b'
|
||||
return "'" + file.replace("'", "'\"'\"'") + "'"
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue