1

I want to pass multiple arguments using cmd to the python script. below is the code I have used.

import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-n', '--names-list', nargs='+', default=[])  
#item1 item2 item3 item4
args = vars(ap.parse_args())

a = args.names-list[0]
b= args.names-list[1]
c=args.names-list[2]
d=args.names-list[3]

print(a)
print(b)
print(c)
print(d)

when I execute the code I got an error message like below.

File "D:\script.py", line 7, in <module>
a = args.names-list[0]
AttributeError: 'dict' object has no attribute 'names'

as I'm very new to this, can somebody help me to solve the problem?

  • See the dupe target: `a = args.names-list[0]` is actually `a = args.names - list[0]`. What you want is `a = args.names_list[0]` – TemporalWolf May 25 '18 at 20:14
  • I disagree that this is a dupe. OP has multiple errors, only one of which is resolved by the duplicate. – Robᵩ May 25 '18 at 20:20
  • @Robᵩ While true, the dupe target also shows the proper usage of parse_args and the dupe does address the specific question asked/error encountered. The answer you wrote is still helpful to the OP I'm sure, but future readers will likely be better served via the dupe. – TemporalWolf May 25 '18 at 20:34
  • When debugging `argparse` it helps to `print(args)` (even before use `vars`). That will show all the attributes, their correct names, and values. – hpaulj May 25 '18 at 20:43

1 Answers1

1

This line is incorrect. You do not need to invoke vars().

args = vars(ap.parse_args())

Instead, try this:

args = ap.parse_args()

Additionally, the argument names are automatically translated from using - to using _. Try this: a = args.names_list[0]

Here is your program, with corrections:

import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-n', '--names-list', nargs='+', default=[])
#item1 item2 item3 item4
args = ap.parse_args()

a = args.names_list[0]
b= args.names_list[1]
c=args.names_list[2]
d=args.names_list[3]

print(a)
print(b)
print(c)
print(d)

And here is the result:

$ python x.py -n one two three four
one
two
three
four
Robᵩ
  • 163,533
  • 20
  • 239
  • 308