How to use input variables with argparse?

Viewed 555

I'm currently working on a Python script where I'd like to have general options. That is because the ultimate goal is to output a URL that has parameters, and each parameter corresponds to an input variable. So maybe the URL has the username parameter, or the date parameter, or the domain parameter, etc. If a user wants to input a username, they can type something like:

script.py -u johndoe

Then the script would take the part after -u, equal it to the variable username, and then insert it into the URL at the appropriate place.

How can I do something like this? I tried doing something with this code, but I don't know where to start, how can I use input variables alongside argparse.

import argparse

parser.add_argument('-u', '--username', action='N', type=str, nargs='+',
                    help='What's the username?')

args = parser.parse_args()
2 Answers

You can try this. If the username is not pass as argument the args.username will be None. If the username is mandatory, you should pass required=True to add_argument(...) call.

import argparse

parser = argparse.ArgumentParser( description="My script")
parser.add_argument('-u', '--username', type=str, 
                    help="What's the username?", required=False)

args = parser.parse_args()

print(args.username)

If I understand your question correctly, I think you want to know how to use the arguments in your program. You can get them by converting them to a dictonary.

args = vars(parser.parse_args())
username = args['username']

So your whole code should look something like this:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-u','--username', help='Some help', required=True)
args = vars(parser.parse_args())
username = args['username']

print(username)
Related