Python中使用字母组合作为参数的组合

6

我想知道是否有一种方法——在互联网上没有找到,但听说是可能的——可以将许多参数作为字母组合在python脚本中获取?我解释一下:如果用户想要发送许多可选参数,例如:如果选项是老虎、青蛙、猫和狗:而不是编写

python ./myScript.py --tiger --frog --cat --dog

撰写:

python ./myScript.py --tfcd

有没有办法做到这一点?

谢谢


我认为 getopt 可以做到这一点(只需一个短横线 -tfcd)使用短选项。 - Jean-François Fabre
1个回答

8

argparse可以接受短参数和长参数。短参数可以组合使用“只要最后一个参数(或没有参数)需要值”。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--tiger', action='store_true')
parser.add_argument('-c', '--cat')
print(parser.parse_args())

使用方法:

>> python test.py -tcToonses
Namespace(cat='Toonses', tiger=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接