Quote POSIX shell special characters in Python output

拜拜、爱过 提交于 2019-12-10 04:35:08

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2692873/quote-posix-shell-special-characters-in-python-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!