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)
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)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With