Skip to content

Instantly share code, notes, and snippets.

@dylnmc
Last active October 14, 2017 20:13
Show Gist options
  • Save dylnmc/f5ce1cfa58fdc3b9af9186dcc2333666 to your computer and use it in GitHub Desktop.
Save dylnmc/f5ce1cfa58fdc3b9af9186dcc2333666 to your computer and use it in GitHub Desktop.
convert rgb to hex from cli
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main(rgb):
if len(rgb) != 3 and len(rgb) != 4:
from sys import stderr, exit
stderr.write('expected either "r g b" or (r,g,b) as input\n')
exit(2)
print("#"+("{:02x}"*3).format(*rgb[:3]))
if __name__ == '__main__':
from sys import argv
if argv[1] in ('--help', '-h'):
from sys import exit
print('RGB 2 HEX!')
print('~~~~~~~~~~')
print('A quick fix cli tool for converting RGB to HEX')
print(' usage: python3 rgb2hex.py [R] [G] [B]')
print(' python3 rgb2hex.py ([R] [G] [B])')
print(' python3 rgb2hex.py \'[R],[G],[B]\'')
print(' python3 rgb2hex.py \'([R],[G],[B])\'')
print()
print(' notes: there should be only either 1 or 3 inputs')
print(' if there is a fourth number, this is ignored')
print(' (useful if there is alpha')
print(' [R], [G], and [B] above represent base 10 numbers')
exit(0)
if len(argv) != 2 and len(argv) != 4:
from sys import stderr, exit
stderr.write('expected either 1 or 3 args\n')
exit(1)
try:
main(tuple(map(lambda s : max(0, min(255, int(s.strip().rstrip(',')))), ','.join(map(lambda s : s.rstrip(','), argv[1:])).strip('()').split(","))))
except ValueError:
from sys import stderr, exit
stderr.write('invalid -- accepted inputs: (r g b) and (r,g,b).\n')
stderr.write('Parens optional and r,g,b must each be base 10 numbers\n')
exit(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment