我的小脚本有问题。我想用参数(--color BLUE
)打开我的程序。
颜色定义如下:
BLUE = bytearray(b'\x00\x00\xff')
解析器如下所示:
common_parser.add_argument('--color', dest='color', action='store', required=False, default=BLUE, help='set the color')
当我现在使用参数 --color YELLOW
启动脚本时,它只读取“Y”并使用它。它不指向字节数组。怎么才能正确通过呢?
最佳答案
定义颜色及其相应对象的字典:
COLORS = {
'BLUE': bytearray(b'\x00\x00\xff'),
'GREEN': bytearray(b'\x00\xff\x00'),
'RED': bytearray(b'\xff\x00\x00')
}
将 add_argument
调用更改为:
common_parser.add_argument('--color', dest='color', required=False, default="BLUE", help='set the color')
现在您可以使用参数按键查找颜色(都是字符串):
color = COLORS[args.color]
其中 args
是从 argparse
解析的命令行参数。
关于python - 如何在Python中正确传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27766278/