在Python输出中引用POSIX shell特殊字符 [英] Quote POSIX shell special characters in Python output

查看:148
本文介绍了在Python输出中引用POSIX shell特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我自动从Python创建小shell脚本,我想确保文件名参数不包含非转义的特殊字符。我已经滚过我自己的解决方案,我将提供一个答案,但我几乎肯定我已经看到这样的功能在标准库中的某个地方丢失。通过丢失我的意思是我没有在一个明显的模块中找到它,例如 shlex cmd subprocess



你知道stdlib中有这样一个函数吗?如果是的,那是在哪里?



即使是负面(但确定和正确的)答案也将被接受。

解决方案

pipes.quote()

 code>>>>从管道导入报价
>>>>引用(一些可怕的string\with有很多垃圾!$$!)
'some\'horrible\\string\\\\withwith很多垃圾!\\ $ \\ $!'

虽然注意到可以说有一个错误,零长度的arg将不会返回任何内容:

 >>> quote()
''

如果它返回''


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

这篇关于在Python输出中引用POSIX shell特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆