Last active
March 30, 2020 17:21
-
-
Save markusdr/49cb2d1ca83642ee57da2678c99a276a to your computer and use it in GitHub Desktop.
Python script template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""A simple python script template. | |
""" | |
from __future__ import print_function | |
import os | |
import sys | |
import argparse | |
import logging | |
def foo(): | |
r'''Example function with test | |
>>> foo() | |
'hello world' | |
''' | |
return 'hello world' | |
def main(arguments): | |
parser = argparse.ArgumentParser( | |
description=__doc__, | |
formatter_class=argparse.RawDescriptionHelpFormatter) | |
parser.add_argument('input', help="Input", type=str, nargs='?', | |
default='-') | |
parser.add_argument('-o', '--output', help="Output", type=str, default='-') | |
parser.add_argument('-t', '--test', help="Execute doctests and exit", | |
action='store_true') | |
parser.add_argument('-d', '--debug', help="Print debugging statements", | |
action="store_const", dest="loglevel", | |
const=logging.DEBUG, default=logging.WARNING) | |
parser.add_argument('-v', '--verbose', help="Verbose output", | |
action="store_const", dest="loglevel", | |
const=logging.INFO) | |
args = parser.parse_args(arguments) | |
logging.basicConfig(level=args.loglevel) | |
# logging.info('Test info output') | |
# logging.debug('Test debug output') | |
input = sys.stdin if args.input == '-' else \ | |
open(args.input, 'r', encoding="utf-8") | |
output = sys.stdout if args.output == '-' else \ | |
open(args.output, 'w', encoding="utf-8") | |
if args.test: | |
import doctest | |
doctest.testmod(verbose=(args.loglevel <= logging.INFO)) | |
sys.exit() | |
if __name__ == '__main__': | |
sys.exit(main(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment