shlex 解析器提供了一个用于指定注释字符的选项,但它在简化的shlex.split 界面中不可用。示例:
import shlex
a = 'hello "bla bla" ; this is a comment'
lex = shlex.shlex(a, posix=True)
lex.commenters = ';'
print(list(lex)) # ['hello', 'bla bla']
这里是一个稍微扩展的split函数,大部分是从Python标准库中复制过来的,对comments参数稍作修改,允许指定注释字符:
import shlex
def shlex_split(s, comments='', posix=True):
"""Split the string *s* using shell-like syntax."""
if s is None:
import warnings
warnings.warn("Passing None for 's' to shlex.split() is deprecated.",
DeprecationWarning, stacklevel=2)
lex = shlex.shlex(s, posix=posix)
lex.whitespace_split = True
if isinstance(comments, str):
lex.commenters = comments
elif not comments:
lex.commenters = ''
return list(lex)
您可能希望更改上述代码中comments 的默认值;正如所写,它与shlex.split 具有相同的默认值,即根本不识别cmets。 (shlex.shlex 创建的解析器对象默认使用# 作为注释字符,如果您指定comments=True,就会得到。我保留此行为是为了兼容。)
注意 cmets 被忽略;它们根本不会出现在结果向量中。当解析器遇到注释字符时,它会停止解析。 (所以永远不可能有两个 cmets。)comments 字符串是可能的 cmets 字符的列表,而不是注释序列。因此,如果您想将# 和; 都识别为注释字符,请指定comments='#:'。
这是一个示例运行:
>>> # Default behaviour is the same as shlex.split
>>> shlex_split("""hello "column number 2" foo ; bar baz""")
['hello', 'column number 2', 'foo', ';', 'bar', 'baz']
>>> # Supply a comments parameter to specify a comment character
>>> shlex_split("""hello "column number 2" foo ; bar baz""", comments=';')
['hello', 'column number 2', 'foo']
>>> shlex_split("""hello "column number 2" foo ;this is a comment; "last one" bye """, comments=';')
['hello', 'column number 2', 'foo']
>>> # The ; is recognised as a comment even if it is not preceded by whitespace.
>>> shlex_split("""hello "column number 2" foo;this is a comment; "last one" bye """, comments=';')
['hello', 'column number 2', 'foo']