Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quote POSIX shell special characters in Python output

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.

like image 402
tzot Avatar asked Apr 22 '10 17:04

tzot


2 Answers

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 '""'.

like image 69
samtregar Avatar answered Nov 07 '22 08:11

samtregar


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.

like image 25
tzot Avatar answered Nov 07 '22 07:11

tzot