Home>
I want to achieve

I want to get the nth array with an argument using argparse.
Only one character is output for the third argument.
"Nargs ='*'" is attached in argparse and it is output firmly as usual.
I don't want to add "nargs ='*'" to the third. What should I do?

import argparse
def TEST (test01, test02, test03):
        a = test01 [0]
        b = test02 [0]
        c = test03 [0]
        print (a)
        print (b)
        print (c)
def main ():
    #Argument processing
    parser = argparse.ArgumentParser (description ='service response')
    parser.add_argument ('-a','--test01', nargs ='*', help ='set a')
    parser.add_argument ('-b','--test02', nargs ='*', help ='set b')
    parser.add_argument ('-c','--test03', help ='set c')
    args = parser.parse_args ()
    TEST (args.test01, args.test02, args.test03)
if __name__ == "__main__":
    main ()
### Run ###
# python3 test.py -a hoge -b hogehoge -c hogehogehoge
# [Output result]
hoge
hogehoge
h
  • Answer # 1

    Correction points

    --c = test03 [0]
    + c = test03
    Cause

    nargs ='*'If, the argument values ​​will be a list. On the other hand, if not specified, it will be a single value instead of a list.

    Only the thirdnargs ='*'Is not specified, sopython3 test.py -a hoge -b hogehoge -c hogehogehogeIf, the content of the argument is

    args.test01 = ["hoge"]
    args.test02 = ["hogehoge"]
    args.test03 = "hogehogehoge"

    However, when outputting

    args.test03 [0]

    Therefore, only the first character of the character string "hogehogehoge" is output.

Trends