Skip to content

Instantly share code, notes, and snippets.

@4383
Last active October 21, 2016 07:31
Show Gist options
  • Save 4383/f7d9803de5b648accff1bac8dbaec113 to your computer and use it in GitHub Desktop.
Save 4383/f7d9803de5b648accff1bac8dbaec113 to your computer and use it in GitHub Desktop.
A pure python command line parser
# -*- coding: UTF-8 -*-
import argparse
import os
from const import BASE_PATH
from const import VERSION
def sample():
pass
def version():
print(VERSION)
class Parser():
"""
Command line parser
"""
__args = None
__instance = None
__command = None
__binding = {'sample': sample, 'version': version}
__parser = None
__subparser = None
__args = None
def __new__(cls):
"""
Singleton
"""
if Parser.__instance is None:
Parser.__instance = object.__new__(cls)
return Parser.__instance
def __init__(self):
"""
Initialize command parser and subcommands
"""
self.__parser = argparse.ArgumentParser(description="Python command line utilities {0}".format(VERSION))
self.__subparser = self.__parser.add_subparsers(description='valid subcommands', help='the sub-command to use')
self.__sample()
self.__version()
self.__args = vars(self.__parser.parse_args())
try:
self.__command = self.__args['which']
except KeyError:
self.__parser.print_help()
exit(1)
def __sample(self):
"""
Sample subcommand for your command line application
"""
start = self.__subparser.add_parser('start', description='Call the sample subcommand')
start.set_defaults(which='sample')
start.add_argument('-opt', '--optionnal', help='optionnal argument')
def __version(self):
"""
Display current version
"""
version = self.__subparser.add_parser('version', description='Display current version')
version.set_defaults(which='version')
def getCommand(self):
"""
Return the selected sub-command
"""
try:
return self.__binding[self.__command]
except KeyError:
print('Unrecognized command !')
self.__parser.print_help()
exit(1)
def getArgs(self):
"""
Return the args of the selected sub-command
"""
return {key: value for key, value in self.__args.items() if key != 'which'}
@4383
Copy link
Author

4383 commented Oct 21, 2016

Project structure:
|-commands
|   | ..__init__.py
|   | ..parser.py
|   |---subcommands
|                 | ..__init__.py
|                 | ..sample.py
|                 | ..version.py
| ..const.py
| ..main.py
|-utilities
          | ..colors.py
          | ..console.py
          | ..__init__.py

@4383
Copy link
Author

4383 commented Oct 21, 2016

#! -*-coding:utf8-*-
from utilities.colors import Colors
"""
utilities.console.py
"""

def display(color, message, following=False):
    """
    Display message on the stdout
    @color: text color
    @message: the message to display
    @following: display next message on the same line 
    """
    message = "{0}{1}{2}".format(color, message, Colors.ENDC)
    if following:
        print(message, end=' ')
    else:
        print(message)


def info(message, following=False):
    '''
    Display information message on the stdout
    '''
    display(Colors.OKBLUE, message, following)


def error(message, following=False):
    """
    Display error message on the stdout
    """
    display(Colors.FAIL, message, following)


def success(message, following=False):
    """
    Display success message on the stdout
    """
    display(Colors.OKGREEN, message, following)


def warning(message, following=False):
    """
    Display warning message on the stdout
    """
    display(Colors.WARNING, message, following)

@4383
Copy link
Author

4383 commented Oct 21, 2016

#!-*-coding:utf8-*-
"""
utilities.colors.py
"""
class Colors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

@4383
Copy link
Author

4383 commented Oct 21, 2016

# -*- coding: UTF-8 -*-

from commands.parser import Parser
from const import SPLASH
from utilities.console import info
from utilities.console import warning


if __name__ == "__main__":
    """
    """
    info(SPLASH)
    try:
        parser = Parser()
        command = parser.getCommand()
        args = parser.getArgs()
        if not args:
            command()
        else:
            command(args)
    except KeyboardInterrupt:
        warning('Execution aborted by user ! Bye !')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment