Cli*_*iff 5 argparse python-3.x
我正在编写一个简单的Python脚本来导出,导入和区分数据库.我想让用户提供他们想要运行脚本的"模式",我选择import,export和diff作为我的选项.当我通过argparse运行它时,所有解析的选项都以args结尾,我可以使用arg.export或args.diff访问它们,但由于"import"是一个关键字,我遇到了问题.
我可以做一些改变的工作,让它工作,但我想知道是否可以保留我拥有的东西.例如,我可以将选项缩短为"exp","imp"和"diff",或者我可以做一个名为"mode"的选项,希望传入"import","export"或"diff".
我目前的代码:
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)
Run Code Online (Sandbox Code Playgroud)
好的,如果我使用“dest”,我仍然可以使用 --import,但让它在内部转到“imp”。
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)
Run Code Online (Sandbox Code Playgroud)