Skip to content

Instantly share code, notes, and snippets.

@jondeaton
Last active March 8, 2018 05:37
Show Gist options
  • Save jondeaton/ffd795fbb2dbb0412f5a9a05c6eb7b3f to your computer and use it in GitHub Desktop.
Save jondeaton/ffd795fbb2dbb0412f5a9a05c6eb7b3f to your computer and use it in GitHub Desktop.
Literally every python script I write
#!/usr/bin/env python
import os, argparse, logging
def parse_args():
parser = argparse.ArgumentParser(description="Super cool thing", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
io_options_group = parser.add_argument_group("I/O Options")
io_options_group.add_argument('-in', "--input", help="Input directory")
io_options_group.add_argument('-out', "--output", help="Output directory")
options_group = parser.add_argument_group("Options")
options_group.add_argument('-p', '--pool-size', type=int, default=16, help="Thread-pool size")
console_options_group = parser.add_argument_group("Console Options")
console_options_group.add_argument('-v', '--verbose', action='store_true', help='verbose output')
console_options_group.add_argument('--debug', action='store_true', help='Debug Console')
console_options_group.add_argument('-log', '--log', nargs='?', default='None', help="Logging file")
return parser.parse_args()
def init_logger(args):
if args.log == 'None': # No --log flag
log_file = None
elif not args.log: # Flag but no argument
log_file = os.path.join("log", os.path.splitext(os.path.basename(__file__))[0] + '_log.txt')
else: # flag with argument
log_file = args.log
if log_file: # Logging file was specified
log_file_dir = os.path.split(log_file)[0]
if log_file_dir and not os.path.exists(log_file_dir):
os.mkdir(log_file_dir)
if os.path.isfile(log_file):
open(log_file, 'w').close()
global logger
if args.debug: log_formatter = logging.Formatter('[%(asctime)s][%(levelname)s][%(funcName)s] - %(message)s')
elif args.verbose: log_formatter = logging.Formatter('[%(asctime)s][%(levelname)s][%(funcName)s] - %(message)s')
else: log_formatter = logging.Formatter('[log][%(levelname)s] - %(message)s')
logger = logging.getLogger(__name__)
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
logger.addHandler(console_handler)
if args.debug: level = logging.DEBUG
elif args.verbose: level = logging.INFO
else: level = logging.WARNING
logger.setLevel(level)
def main():
args = parse_args()
init_logger(args)
# code goes here...
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment