简体   繁体   中英

How do I pass the argument correctly in Python

I have a Problem with my a little script. I want to open my program with an argument ( --color BLUE ).

The color is defined like this:

BLUE = bytearray(b'\x00\x00\xff')

The parser looks like this:

common_parser.add_argument('--color', dest='color', action='store', required=False, default=BLUE, help='set the color')

When I now start the script with the argument --color YELLOW it only read the "Y" and works with it. It does not point at the bytearray. How can I pass it correctly?

Define a dictionary of colors and their corresponding objects:

COLORS = {
    'BLUE': bytearray(b'\x00\x00\xff'),
    'GREEN': bytearray(b'\x00\xff\x00'),
    'RED': bytearray(b'\xff\x00\x00')
}

Change the add_argument call to:

common_parser.add_argument('--color', dest='color', required=False, default="BLUE", help='set the color')

Now you can use the argument to find the color by key (both are strings):

color = COLORS[args.color]

Where args are the parsed command-line arguments from argparse .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM