Created
May 18, 2019 18:35
-
-
Save bbengfort/badb12824e9cbe2d8f5634323d7ee6cc to your computer and use it in GitHub Desktop.
Argparse example of color conversion in SE 2019-05-18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
def hex2rgb(color): | |
color = color.lstrip("#") | |
return tuple( | |
int(color[idx:idx+2], 16) | |
for idx in (0, 2, 4) | |
) | |
def rgb2hex(color): | |
return "#{0:02x}{1:02x}{2:02x}".format(*color) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser( | |
description = "awesome color parser of awesomeness", | |
epilog = "if any problems talk to Michael definitely not Ben" | |
) | |
parser.add_argument( | |
"-r", "--rgb", action="store_true", default=False, | |
help="convert an rgb value to hex" | |
) | |
parser.add_argument( | |
"-x", "--hex", action="store_true", default=False, | |
help="convert hex colors to rgb" | |
) | |
parser.add_argument( | |
"colors", type=str, nargs="+", metavar="color", | |
help="pass one or more hex values or 3 RGB values" | |
) | |
# Get the args from the command line | |
args = parser.parse_args() | |
if args.rgb: | |
if len(args.colors) % 3 != 0: | |
parser.error("please provide 3 RGB arguments for each color") | |
try: | |
colors = [ | |
int(color) for color in args.colors | |
] | |
except ValueError: | |
parser.error("RGB requires all int values") | |
for idx in range(0, len(colors), 3): | |
rgb = colors[idx:idx+3] | |
print(rgb2hex(rgb)) | |
elif args.hex: | |
for color in args.colors: | |
print(hex2rgb(color)) | |
else: | |
parser.error("specify --rgb or --hex") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment