7

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.
Anarion
  • 2,406
  • 3
  • 28
  • 42

1 Answers1

5

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
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • So, args is a dictionary of tuples? How do I delete an element from dictionary based only on one value of a tuple? – Anarion Oct 17 '13 at 15:13
  • Thanks so much, that's what I needed but wasn't sure how to do. – Anarion Oct 17 '13 at 15:16
  • 1
    @Anarion: `args.items()` returns a list of key-value pairs. `if k != 'archive'` keeps items where the key is not `'archive'`. `dict` builds a new dictionary out of the resulting tuples (`k, v`). Removing a key is more straightforward: `del args[key]` removes the key from the dictionary. If this answer is helpful, please consider accepting the answer. – Steven Rumbalski Oct 17 '13 at 15:18
  • 2
    `args` from `parse_args` is not a dictionary. It is a simple `argparser.Namespace` object. `vars(args)` is a dictionary (with methods like `.items()`. – hpaulj Sep 27 '15 at 15:21
  • Your first code fragment has a syntax error: You need to parenthesise the `k, v` pair: `dict((k, v) for k, v in ...)`. Otherwise it looks like `k` is the first argument to `dict()`, followed by a generator expression (which is not allowed). – lenz Jan 09 '16 at 11:15