0

I am trying to parse arguments passed from command line.I am passing 15 arguments at all. I am trying to group those by giving them same destination () I need to group those. Now when I print input i get lists f.e [mylogo.png, otherlogo.png] and so on. How I could get a result similar to {destination:'value1','value2'} . I know I could do it manually but It's not a solution in my case..

   parser = argparse.ArgumentParser(prog='Moodle automation', add_help= False,
                                     description=description(), usage='nana nanan nana')
   parser.add_argument('-logo', '--set_logo',
                        help='',
                        dest='branding',
                        type=str,
                        action='append')

    parser.add_argument('-c_logo', '--set_compact_logo',
                        help='',
                        dest='branding',
                        type=str,
                        action='append'
                        )


    web_status.add_argument('-wn', '--web_new',
                            help=" ",
                            dest='web_state',
                            action="append")

    web_status.add_argument('-wo', '--web_old',
                            help="",
                            dest="web_state",
                            action="append")
    args = parser.parse_args()
     branding_details = args.branding
     print(branding_details)

in case input:

program.py -logo mylogo.png -c_logo custom_logo.png

I get output ['mylogo.png', 'custom_logo.png']

mike
  • 101
  • 1
  • 15
  • https://stackoverflow.com/questions/30487767/check-if-argparse-optional-argument-is-set-or-not? Then check if `args.arg1 is not None and args.arg2 is not None` – Peter S May 04 '20 at 23:43
  • With that setup you'll get two: `args.branding` and `args.web_state`. With `append` you should get lists (if not the default `None`). – hpaulj May 05 '20 at 00:01
  • I think you missed the important part in question. Exactly which statements you are using to parse and print the arguments provided over command line? – Tejas Sarade May 05 '20 at 00:10
  • What's `web_status`? You code bits leave too many ambiguitities. – hpaulj May 05 '20 at 00:47
  • @TejasSarade I editted my question. Copy paste issue.. – mike May 05 '20 at 05:34

2 Answers2

1

If you just print(vars(args)), it will give output like this. vars() is always a handy function if you are dealing with object names.

{'branding': ['mylogo.png', 'custom_logo.png']}

It is just matter of removing those square brackets [] from output and if you are using multiple destinations, you can iterate over the args dictionary to get desired output.

args_dict = vars(args)
for k, v in args_dict.items():
    print("{", k, ":", str(v).strip('[]'), "}")

output:

{ branding : 'mylogo.png', 'custom_logo.png' }

OR even better formatting with

args_dict = vars(args)
for k, v in args_dict.items():
    print('{{{0}: {1}}}'.format(k, str(v).strip('[]')))

output:

{branding: 'mylogo.png', 'custom_logo.png'}
Tejas Sarade
  • 1,144
  • 12
  • 17
0

Here is a complete minimal example, where we can give several logo and compact_logo with nargs='*'. The result contains lists of arguments.

cli represents an example string you would to pass to the program.

import argparse
parser = argparse.ArgumentParser(prog='Moodle automation', add_help= False,
                                 description='', usage='nana nanan nana')
parser.add_argument('-l', '--set_logo',
                    help='',
                    dest='logo',
                    nargs='*',
                    type=str)

parser.add_argument('-c', '--set_compact_logo',
                    help='',
                    dest='compact_logo',
                    nargs='*',
                    type=str)

cli = '-l mylogo.png -c custom_logo_1.png custom_logo_2.png'
args = parser.parse_args(cli.split())
print("List of arguments")
print(args.logo)
print(args.compact_logo)
print("Create a dict of key values for arguments")
dict_key_args = {key: value for key, value in args._get_kwargs()}   
# Create the following data structure
# {'compact_logo': ['custom_logo_1.png', 'custom_logo_2.png'],
# 'logo': ['mylogo.png']}      
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49