Skip to content

Instantly share code, notes, and snippets.

@gcaracuel
Last active April 17, 2018 08:35
Show Gist options
  • Save gcaracuel/7185ab0ff09bf2220dfbdac37255dda3 to your computer and use it in GitHub Desktop.
Save gcaracuel/7185ab0ff09bf2220dfbdac37255dda3 to your computer and use it in GitHub Desktop.
[Python] UNIX command skeleton - Python 3
#!/usr/bin/env python3
"""
SYNOPSIS
TODO: Resumed description [-h,--help] [-v,--verbose] [--version]
DESCRIPTION
TODO This describes how to use this script. This docstring
will be printed by the script if there is an error or
if the user requests help (-h or --help).
EXAMPLES
TODO: Show some examples of how to use this script.
EXIT STATUS
TODO: List exit codes
AUTHOR
Guillermo Caracuel <gcaracuel|at|gmail|dot|com>
LICENSE
GPL
VERSION
0.1
Python --version > 3
"""
import sys
import traceback
import argparse
import time
import logging
def main():
global options, args
# TODO: Place here your code
if __name__ == '__main__':
try:
start_time = time.time()
parser = argparse.ArgumentParser(description='TODO')
parser.add_argument('-v', '--verbose', action='count',
default=False, help='verbose output. Use -vv/-vvv for extra verbosity')
# Example of optional argument: parser.add_argument ('-p', '--password', action='store', help='Hello!', default="_")
# Example of sorted argument: parser.add_argument ('username', metavar='username', action='store', help='Hello!')
args = parser.parse_args()
# Arguments could be accesed as 'args.password or args.username'
# Logging configuration
if args.verbose == 1:
loglevel=logging.INFO
elif args.verbose >= 2:
loglevel=logging.DEBUG
else:
loglevel=logging.WARNING
root = logging.getLogger()
root.setLevel(loglevel)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(loglevel)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
# Log to file
# fileHandler = logging.FileHandler("execution.log")
# fileHandler.setFormatter(formatter)
# root.addHandler(fileHandler)
# Execution STARTS
logging.debug('EXECUTION STARTS')
start_time = time.asctime()
main()
logging.debug('TOTAL TIME OF EXECUTION IN MINUTES: ' + str(round((time.time() - start_time) / 60.0,2)))
sys.exit(0)
except KeyboardInterrupt as e: # Ctrl-C
raise e
except SystemExit as e: # sys.exit()
raise e
except Exception as e:
logging.error('ERROR, UNEXPECTED EXCEPTION')
logging.error(str(e))
traceback.print_exc()
sys.exit(1)
@gcaracuel
Copy link
Author

This gist relates to it's Python 2 version available at: https://gist.github.com/gcaracuel/10271809

@gcaracuel
Copy link
Author

Changed this script to use logging so it's much easier to move it's output to a file or both log file and stdout.

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