Skip to content

Instantly share code, notes, and snippets.

@freejoe76
Last active June 2, 2021 02:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freejoe76/7af5a3d88766f3ae6fa0c77bacaa002a to your computer and use it in GitHub Desktop.
Save freejoe76/7af5a3d88766f3ae6fa0c77bacaa002a to your computer and use it in GitHub Desktop.
My python boilerplate

These files, as written, are aimed at command-line execution, but because if __name__ == '__main__': only fires when run on the command line, it can also be included in another python script if need be.

It uses doctests (which fire when run from the command line with a -t / --test flag) because I like doctests because they're the simplest way to add tests to your code, and tests in your code are a good way to help remind future-you how current-you imagined you'd be using the code you wrote.

The code you want to execute goes in the main() method.

#!/usr/bin/env python3
# Describe what this does in one line for people who might run head on this file.
import os, sys
import argparse
import doctest
import pdb
def main(args):
""" Handle the command line.
"""
pass
def build_parser(args):
""" Handle the argparse and make it testable.
>>> args = build_parser(['--verbose'])
>>> print(args.verbose)
True
"""
parser = argparse.ArgumentParser(usage = '$ python project.py',
description='''.''',
epilog='')
parser.add_argument('-v', '--verbose', dest='verbose', default=False, action='store_true')
parser.add_argument('-t', '--test', dest='test', default=False, action='store_true')
#parser.add_argument('items', nargs='*', default=[1, 2, 3], help='')
args = parser.parse_args(args)
return args
if __name__ == '__main__':
args = build_parser(sys.argv[1:])
if args.test == True:
doctest.testmod(verbose=args.verbose)
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment