Skip to content

Instantly share code, notes, and snippets.

@Avantol13
Last active May 28, 2016 21:39
Show Gist options
  • Save Avantol13/ce5b2b1eca8b084f79d1095e26a8bf68 to your computer and use it in GitHub Desktop.
Save Avantol13/ce5b2b1eca8b084f79d1095e26a8bf68 to your computer and use it in GitHub Desktop.
Simple example of a command line interface for Python using argparse and colorama
#!/usr/bin/env python3
'''
Pretty Command Line Interface Example v1.1
@author: Alexander VanTol
'''
import sys
import traceback
import argparse
from colorama import init, Fore, Back, Style
def main():
# Initialize the colorma colored command line output
init()
# Parse arguments into script. Note that 1st argument is script name
args = parse_args(sys.argv[1:])
print_header()
# Arguments can be accessed via their names as defined in the add_argument
# method of ArgumentParser
print('You entered:')
for item in args.required:
print(Fore.GREEN + '"' + item + '"')
print(Fore.RESET + 'as the required argument(s).\n')
# User supplied optional argument to command line
if args.optional:
# Argument must be accessed by full name
print('You entered ' + Fore.GREEN + '"' + args.optional + '"' +
Fore.RESET + ' as an optional argument.\n')
# User supplied force error argument to command line
if args.error_force:
try:
print(Back.LIGHTRED_EX + Fore.BLACK + 'Forcing error...' +
Back.RESET + Fore.RESET + '\n')
impossible = 5 / 0
print(impossible)
except Exception:
print_error('You can print a custom message here.\n')
# Force exit
sys.exit()
print_footer()
def parse_args(args):
"""
Returns parsed and validated arguments that were passed into the script.
:param args: The arguments passed into the script
"""
# Parse arguments from command line
parser = argparse.ArgumentParser()
# Add a new required argument(s) with display of r in help. Remove nargs
# argument if multiple entries not allowed. Only requires a single entry,
# but user can enter multiple
parser.add_argument('required', metavar='r', type=str, nargs='+',
help='At least one argument is required')
# Define an optional command line argument that accepts a value
parser.add_argument('-o', '--optional', help='This argument is optional')
# Define an optional command line argument that does not accept a value
parser.add_argument('-e', '--error_force', help='Intentionally cause error',
action='store_true')
return parser.parse_args()
def print_header():
"""
Print header of tool into command line.
"""
print(Style.BRIGHT + '\n--------------------------------------------------'
+ '------------------------------')
print(' COMMAND LINE INTERFACE EXAMPLE')
print('-------------------------------------------------------------------'
+ '-------------\n' + Style.RESET_ALL)
def print_footer():
"""
Print footer of tool into command line.
"""
print(Style.BRIGHT + '\n--------------------------------------------------'
+ '------------------------------')
print(' END')
print('-------------------------------------------------------------------'
+ '-------------\n' + Style.RESET_ALL)
def print_error(error=None):
"""
Print an error into command line with traceback.
:param error: Optional string to print before traceback
"""
print(Fore.RED + Style.BRIGHT + '!!!--------------------------------------'
+ '------------------------------------!!!\n')
if error is not None:
print(error + '\n')
traceback.print_exc()
print('\n!!!--------------------------------------------------------------'
+ '------------!!!' + Style.RESET_ALL + '\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment