Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a python keyword as an option in argparse

I am writing a simple Python script to export, import and diff against a database. I want to have the user supply the "mode" they want to run the script in, and I chose import, export and diff as my options. When I run it through argparse, all of the parsed options end up in args, and I can access them using arg.export or args.diff, but since "import" is a keyword, I run into problems.

There are a couple of work-arounds I could do instead, to make it work, but I want to know if it's possible to keep what I have. For example, I could shorten the options to "exp", "imp" and "diff", or I could do an option called "mode" that expects "import", "export" or "diff" to be passed in.

My current code:

parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument("--export", help="Export source(s)", action="store_true")
group.add_argument("--import", help="Import source(s)", action="store_true")
group.add_argument("--diff", help="Diff sources", action="store_true")

parser.add_argument("filename", help="XML Filename used for exporting to, importing from or comparing while doing diff.")

args = parser.parse_args()

if args.export:
    export_sources(args.filename)
elif args.import:
    import_sources(args.filename)
elif args.diff:
    diff_sources(args.filename)
like image 947
Cliff Avatar asked Mar 30 '13 03:03

Cliff


2 Answers

Okay, if I use "dest", I can still use --import, but have it go to "imp" internally.

    parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument("--export", help="Export source(s)", action="store_true")
group.add_argument("--import", dest="imp", help="Import source(s)", action="store_true")
group.add_argument("--diff", help="Diff sources", action="store_true")

parser.add_argument("filename", help="XML Filename used for exporting to, importing from or comparing while doing diff.")

args = parser.parse_args()

if args.export:
    export_sources(args.filename)
elif args.imp:
    import_sources(args.filename)
elif args.diff:
    diff_sources(args.filename)
like image 79
Cliff Avatar answered Nov 15 '22 08:11

Cliff


You can access the parsed arguments also with getattr:

parser = argparse.ArgumentParser()
parser.add_argument('--import')
args = parser.parse_args()
import_value = getattr(args, 'import', None)  # defaults to None

Or check for the existence of the argument and then read it into a variable:

# [...]
if hasattr(args, 'import'):
    import_value = getattr(args, 'import')
like image 32
Ricky Robinson Avatar answered Nov 15 '22 09:11

Ricky Robinson