我的项目之一使用了shlex.quote从python 3.3开始可用的功能。但这shlex.quote与pipes.quote移至shlex之后已弃用的相同。
现在为了兼容性,我使用以下代码:
defcmd_quote(string):importsysifint(sys.version[2])<3:importpipesreturnpipes.quote(string)else:importshlexreturnshlex.quote(string)
是否存在更好的做法?
解决方案
首先,如果要对版本进行数值比较,请使用version_info,不要尝试解析version。*中的字符串。
这也意味着您可以利用元组的比较方式并编写如下代码:
ifsys.version_info
……如果Python达到3.10.0或4.0,它也不会中断。
*除非您需要担心1.5与2.0对比,否则在这种情况下,您显然已经在Usenet和StackOverflow之间建立了时间机器网关,并且可以肯定的是,您可以想到更好的用法。
无论如何,最好首先测试一下shlex.quote现有资源。这样,对读者来说您正在做什么很明显:shlex.quote如果可能,使用,pipes.quote如果不使用,则使用。
You'll see that pattern all over the place—even in the stdlib, where code is imported from C accelerator modules if possible, but fallback code is used if not (e.g., if you're usi