Python. Argparser. Removing not-needed arguments

安稳与你 提交于 2019-12-07 03:40:14

问题


I am parsing some command-line arguments, and most of them need to be passed to a method, but not all.

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dir", help = "Directory name", type = str, default = "backups")
parser.add_argument("-n", "--dbname", help = "Name of the database", type = str, default = "dmitrii")
parser.add_argument("-p", "--password", help = "Database password", type = str, default = "1123581321")
parser.add_argument("-u", "--user", help = "Database username", type = str, default = "Dmitriy")
parser.add_argument("-a", "--archive", help = "Archive backup", action="store_true")
args = parser.parse_args()

backup(**vars(args)) # the method where i need to pass most of the arguments, except archive. Now it passes all.

回答1:


Either create a new dictionary that does not have that key:

new_args = dict(k, v for k, v in args.items() if k != 'archive')

Or remove the key from your original dictionary:

archive_arg = args['archive'] # save for later
del args['archive'] #remove it


来源:https://stackoverflow.com/questions/19430496/python-argparser-removing-not-needed-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!