Created
November 1, 2018 18:48
-
-
Save digitalist/eabffef448e6dc5b2ffdf746502cbda0 to your computer and use it in GitHub Desktop.
Python 3 argparse boilerplate
This file contains hidden or 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
| import os | |
| import sys | |
| import argparse | |
| import logging | |
| APPNAME_LOCK_FILE_NAME = "PY-BOILERPLATE" | |
| def argparse_str2bool(v): | |
| """ | |
| allows handy parsing of bool args for argparse | |
| https://stackoverflow.com/a/43357954/5006740 | |
| :param v: | |
| :return: | |
| """ | |
| if not isinstance(v, str): | |
| return v | |
| if v.lower() in ('yes', 'true', 't', 'y', '1'): | |
| return True | |
| elif v.lower() in ('no', 'false', 'f', 'n', '0'): | |
| return False | |
| else: | |
| raise argparse.ArgumentTypeError('Boolean value expected.') | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| subparsers = parser.add_subparsers() | |
| parser.add_argument('--example1', default=1) | |
| parser.add_argument('--example2', default=0) | |
| args = parser.parse_args() | |
| # looks like boilerplate :-) | |
| args.example1 = argparse_str2bool(args.example1) | |
| args.example2 = argparse_str2bool(args.example1) | |
| print(args) | |
| if __name__ == "__main__": | |
| # WITH LOCK with locket | |
| # import locket | |
| # try: | |
| # with locket.lock_file(f"/tmp/{APPNAME_LOCK_FILE_NAME}.lock", timeout=0): | |
| # main() | |
| # except locket.LockError as e: | |
| # logging.info('Script is already running') | |
| # WITHOUT LOCK: | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment