Using python keyword as option in argparse

I am writing a simple Python script to export, import and map to a database. I want the user to provide the "mode" that they want to run the script, and I chose import, export and diff as my parameters. When I run it through argparse, all parsed parameters end up in args, and I can access them using arg.export or args.diff, but since import is a keyword, I'm having problems.

There are a few workarounds that I could do instead to make it work, but I want to know if I can keep what I have. For example, I could shorten the options to "exp", "imp" and "diff", or I could make the option "mode", which expects the transfer of "import", "export" or "diff".

My current code is:

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) 
+4
source share
2 answers

Well, if I use "dest", I can still use -import, but go to "imp" inside.

  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) 
+4
source

You can also access the parsed arguments 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 argument, and then read it in the variable:

 # [...] if hasattr(args, 'import'): import_value = getattr(args, 'import') 
+1
source

All Articles