views:

178

answers:

2

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.

A: 

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.

ΤΖΩΤΖΙΟΥ
Isn't it infuriating when you ask a question just to answer it, and it was a dupe in the first place? :P (Happened to me just recently, too.)
Roger Pate
@Roger: Hell. The search mechanism of SO needs improvements. I *did* search for an answer before asking. Note that my answer was never intended to be chosen as *the* answer. I also voted for closing the question.
ΤΖΩΤΖΙΟΥ
[Indeed, it does.](http://meta.stackoverflow.com/questions/42878/show-related-questions-just-before-question-submission) I wasn't trying to say anything bad about your asking the question (it can even be hard to search until after all the thought processes that went into writing and posting), just trying to share the frustration.
Roger Pate
+3  A: 

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

samtregar
Yes, thank you! And it is in an obvious module (for a POSIX user), so I was mistaken.
ΤΖΩΤΖΙΟΥ