Created
August 8, 2016 17:15
-
-
Save peteristhegreat/f6f723e34611ee86c60cee50c52fea72 to your computer and use it in GitHub Desktop.
getopt python commandline arguments parameters usage verbose help dry-run - all in one example
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
#!/usr/bin/env python | |
# This file is intended to be a quick template for making a commandline tool in python using getopt to hande the arguments. | |
import sys, os, re, getopt | |
def usage(): | |
# output comparable to argparse | |
# https://docs.python.org/2/library/argparse.html#module-argparse | |
filename = os.path.basename(__file__) | |
print """ | |
usage: {file} [OPTIONS] | |
options: | |
-h, --help, -? Print this usage info | |
-v, --verbose Verbose output | |
-n, --dry-run Don't write changes | |
""".format(file=filename) | |
def main(args_in): | |
print args_in | |
# https://docs.python.org/2/library/getopt.html | |
try: | |
opts, args = getopt.getopt(args_in,"h?vn",["help","verbose","dry-run"]) | |
except getopt.GetoptError as err: | |
print str(err) | |
usage() | |
sys.exit(2) | |
verbose = 0 | |
dry_run = False | |
for o, a in opts: | |
if o in ("-h","--help","-?"): | |
usage() | |
sys.exit() | |
elif o in ("-v","--verbose"): | |
verbose += 1 | |
elif o in ("-n","--dry-run"): | |
dry_run = True | |
else: | |
assert False, "unhandled option: {0}".format(o) | |
if verbose > 0: | |
print "verbose is on!" | |
if not dry_run: | |
# do execute here | |
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