gpt4 book ai didi

python-3.x - 在 argparse 中使用 python 关键字作为选项

转载 作者:行者123 更新时间:2023-12-04 18:45:12 26 4
gpt4 key购买 nike

我正在编写一个简单的 Python 脚本来导出、导入和比较数据库。我想让用户提供他们想要运行脚本的“模式”,我选择导入、导出和差异作为我的选项。当我通过 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)

最佳答案

好的,如果我使用“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)

关于python-3.x - 在 argparse 中使用 python 关键字作为选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15714597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com