6

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 1
    possible duplicate of [What's the best way to escape os.system() calls in Python?](http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-os-system-calls-in-python) – Even though the other is talking about os.system and this isn't, it's the same quoting for the same purpose. And it has the same answers. –  Oct 03 '10 at 20:12

2 Answers2

6

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
  • 6,888
  • 3
  • 21
  • 17
  • Yes, thank you! And it is in an obvious module (for a POSIX user), so I was mistaken. – tzot Apr 22 '10 at 17:23
  • Sometimes `subprocess.list2cmdline` is also useful; it does *not* escape shell metachars but does handle escaping quoting and escaping spaces, so it's quite good when you *want* to invoke a remote shell but it's passing through one or more additional layers of de-escaping on the way, like via `ssh` remote command invocation. – Craig Ringer May 23 '13 at 02:50
1

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 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.) –  Oct 03 '10 at 20:37
  • @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. – tzot Oct 03 '10 at 21:19
  • 1
    [Indeed, it does.](http://meta.stackexchange.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. –  Oct 04 '10 at 04:33