There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard library. By “lost” I mean I didn't find it in an obvious module like shlex
, cmd
or subprocess
.
Do you know of such a function in the stdlib? If yes, where is it?
Even a negative (but definite and correct :) answer will be accepted.
pipes.quote()
:
>>> from pipes import quote
>>> quote("""some'horrible"string\with lots of junk!$$!""")
'"some\'horrible\\"string\\\\with lots of junk!\\$\\$!"'
Although note that it's arguably got a bug where a zero-length arg will return nothing:
>>> quote("")
''
Probably it would be better if it returned '""'
.
The function I use is:
def quote_filename(filename):
return '"%s"' % (
filename
.replace('\\', '\\\\')
.replace('"', '\"')
.replace('$', '\$')
.replace('`', '\`')
)
that is: I always enclose the filename in double quotes, and then quote the only characters special inside double quotes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With