Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import sys
- import string
- def h2i(rgbOctet):
- """
- Return the Base 10 value for a hex (base 0) octet
- """
- return (int('0x%s' % ( rgbOctet ), 0))
- def validate_hex_string( hexString ):
- """
- Loop through a hex string and validate that each character
- in the string is a valid hex character.
- """
- # Set default return status to True
- status = True
- # If the hexString is 4 or 7 characters long, strip off
- # the leading character, as it is going to be a '#'
- if hexString[0] == '#':
- if len( hexString ) in ( 4, 7 ):
- hexString = hexString[1:]
- # If the hexString is not 6 characters long
- if len( hexString ) not in ( 3, 6 ):
- # Print error to stderr
- print >> sys.stderr, 'Error: \n\tArguement should be 6 hexidecimal characters, and may contain a leading # symbol.\n\tAnything else is considered invalid.\n\tExiting.'
- # Exit with non-zero status code
- sys.exit(1)
- # If the length is 3, add padding
- if len( hexString ) == 3:
- hexString = '%s%s%s%s%s%s' % ( hexString[0], hexString[0], hexString[1], hexString[1], hexString[2], hexString[2] )
- # Loop through the string and validate character-by-character
- # Set return value to false if invalid character(s) detected
- for i in hexString:
- # If character is not in string.hexdigits ( a list of valid hex characters )
- if i not in string.hexdigits:
- # Print which character and its placement to stderr
- print >> sys.stderr, 'Error: \n\tCharacter %d (%c) not a valid hex character.' % ( sys.argv[1].index(i), i )
- # Set return status to false
- status = False
- # If status is still true, return hexString
- if status:
- return hexString
- # If status is false, return False
- else:
- return status
- # If the validation returns non-False, run the conversion
- if validate_hex_string( sys.argv[1] ):
- # Set a to the return status of validator
- a = validate_hex_string( sys.argv[1] )
- # Break up each color's octet
- red = a[:2]
- green = a[2:4]
- blue = a[4:6]
- # Print the original value
- print "Hex value: %s" % ( a )
- # Print the converted value
- print "RGB Value: rgb( %d, %d, %d )" % ( h2i(red), h2i(green), h2i(blue) )
- # If errors are detected during validation, Exit
- else:
- sys.exit('\nExiting due to invalid H\exidecimal characters being detected.')
Add Comment
Please, Sign In to add comment