You can download this code by clicking the button below.
This code is now available for download.
This function uses the Argparse library to parse command line arguments and outputs a random color in hexadecimal or RGB format based on the settings of the arguments.
Technology Stack : Python, Argparse, Colorsys
Code Type : Python Function
Code Difficulty : Intermediate
import argparse
def generate_random_color(arg1, arg2):
parser = argparse.ArgumentParser(description='Generate a random color.')
parser.add_argument('--hex', action='store_true', help='Output color in hexadecimal format.')
parser.add_argument('--rgb', action='store_true', help='Output color in RGB format.')
args = parser.parse_args(arg1, arg2)
import random
from colorsys import hls_to_rgb
# Generate a random hue
hue = random.random()
# Convert HLS to RGB
l = 0.5
s = 0.5
v = 0.95
r, g, b = hls_to_rgb(hue, l, v)
if args.hex:
return '#{:02x}{:02x}{:02x}'.format(int(r * 255), int(g * 255), int(b * 255))
else:
return '{:.2f}, {:.2f}, {:.2f}'.format(r, g, b)