python - 如何在Python中正确传递参数

标签 python

我的小脚本有问题。我想用参数(--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/

相关文章:

python - cc1plus : out of memory when building dlib

python - 为什么我的简单 python gtk+cairo 程序运行如此缓慢/断断续续?

python ArgumentParser - 错误 : unrecognized arguments: ip_2 '127.0.0.1' `

python 类只读属性(在日期时间)

python - 如何在 matplotlib 中的每个子图上嵌入图像?

python - Pandas 在数据框和系列(列)之间相乘

Visual Studio 中的 Python 2.7.11 在 cElementTree.py 中抛出异常

python - XPath 删除列表 Python 中的空格

python - PIL 剪贴板图像到 Base64 字符串

python - 类型错误 : forward() missing 1 required positional argument: 'hidden'