在Python中解析标志

3 投票
1 回答
1116 浏览
提问于 2025-04-28 04:44

我正在尝试手动解析一个字符串中的参数和标志。

比如说,如果我有一个字符串:

"--flag1 'this is the argument'"

我希望得到的结果是:

['--flag1', 'this is the argument']

也就是说,无论字符串中有多少个标志,我都想得到这样的结果。

我遇到的困难是如何处理包含多个单词的标志参数。

举个例子,如果我这样做(parser 是从 argparse 引入的):

parser.parse_args("--flag1 'this is the argument'".split())

那么 "--flag1 'this is the argument'".split() 的结果会变成:

['--flag1', "'this", 'is', 'the', "argument'"]

这并不是我所期望的结果。有没有简单的方法可以做到这一点呢?

暂无标签

1 个回答

8

你真幸运;其实有一个简单的方法可以做到这一点。使用 shlex.split。这个方法可以按照你想要的方式来分割字符串。

>>> import shlex
>>> shlex.split("--flag1 'this is the argument'")
['--flag1', 'this is the argument']

撰写回答