Python Forum

Full Version: How can I get some arguments using argparse?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am using a module argparse. I need to get arguments and then do something. I can only one argument now, but I cannot get some arguments if an user types two arguments.

python demo.py -c work.txt
Now here is my code:
import sys, argparse

def main():
    parser = argparse.ArgumentParser(description="Process some ...")
    #parser.add_argument('-n', '--name', required=True, help="name of the user")
    parser.add_argument('-n', '--name', required=False, help="name of the user")
    parser.add_argument('-a', '--adress', required=False, help="name of the host")
    parser.add_argument('-c', '--copy', required=False, help="Copy a file into a server")

    args = vars(parser.parse_args())
    #if args
    for x in args.values():
        if x != None:
            print(x)

main()
I can get them list_args like that:
python demo.py -a Russia -c work.txt
    args = vars(parser.parse_args())
    list_args = []
    for x in args.values():
        if x != None:
            list_args.append(x)

    print(list_args)
but then I cannot understand where who is.
How to do it?

OMG! I resolved it.
import argparse

def main():
    parser = argparse.ArgumentParser(description="Process some ...")

    parser.add_argument('-n', '--name', required=False, help="name of the user")
    parser.add_argument('-a', '--adress', required=False, help="name of the host")
    parser.add_argument('-c', '--copy', required=False, help="Copy a file to the server")

    args = vars(parser.parse_args())

    if args['name']:
        print('i am name {}'.format(args['name']))

    if args['adress']:
        print('i am adress {}'.format(args['adress']))

    if args['copy']:
        print('i am copy {}'.format(args['copy']))




main()