python argparse 传递分隔列表

2 投票
3 回答
3878 浏览
提问于 2025-04-18 08:19

下面是一些内容:

parser.add_argument("-l", "--library", type=str, nargs="*", dest="scanLibrary")

在传递的名字列表中,有可能会包含空格。argparse会根据空格来分割这个列表,所以

mything.py -l test of foo, game of bar, How I foo bar your mother

我得到了:

scanLibrary=['test', 'of', 'foo,', 'game', 'of', 'bar,', 'How', 'I', 'foo', 'bar', 'your', 'mother']

那么我该如何让argparse使用我选择的分隔符呢?

更新:根据Martijn Pieters的建议,我做了以下更改:

parser.add_argument("-l", "--library", type=str, nargs="*", dest="scanLibrary")
print args.scanLibrary
print args.scanLibrary[0].split(',')

这给出了这样的结果:

mything.py -l "test of foo, game of bar, How I foo bar your mother"
['test of foo, game of bar, How I foo bar your mother']
['test of foo', ' game of bar', ' How I foo bar your mother']

我可以很容易地清理掉前面的空格。谢谢!

3 个回答

1

我不能在你的问题下评论,因为需要50个回复才能评论。我只是想说,你可以使用:

'   some string '.strip()

来得到:

'some string'
2

在我看来,有一个更好的方法可以做到这一点,那就是使用一个叫做“lambda函数”的东西。这样的话,你就不需要在处理完列表后再进行额外的操作,这样可以让你的代码看起来更整洁。你可以这样做:

# mything.py -l test of foo, game of bar, How I foo bar your mother

parser.add_argument("-l",
                    "--library",
                    type=lambda s: [i for i in s.split(',')],
                    dest="scanLibrary")

print(args.scanLibrary)

# ['test of foo', 'game of bar', 'How I foo bar your mother']
2

你不能这样做。这里是命令行解释器在处理这些内容;它会把参数作为一个解析过的列表传递给程序。

为了避免这个问题,你可以把你的参数用引号括起来:

mything.py -l "test of foo, game of bar, How I foo bar your mother"

撰写回答