Skip to content Skip to sidebar Skip to footer

Pass Command Line Argument To Python Script

I have a file.py that I want to pass base_url to when called, so that base_url variable value can be dynamic upon running python file.py base_url='http://google.com' the value of

Solution 1:

The command line arguments are stored in the list sys.argv. sys.argv[0] is the name of the command that was invoked.

import sys

iflen(sys.argv) != 2:
    sys.stderr.write("usage: {} base_url".format(sys.argv[0]))
    exit(-1) # or deal with this case in another way
base_url_arg = sys.argv[1]

Depending on the input format, base_url_arg might have to be further processed.

Solution 2:

sys.argv.

How to use sys.argv in Python

For parsing arguments passed as "name=value" strings, you can do something like:

import sys

args = {}
for pair in sys.argv[1:]:
    args.__setitem__(*((pair.split('=', 1) + [''])[:2]))

# access args['base_url'] here

and if you want more elaborate parsing of command line options, use argparse.

Here's a tutorial on argparse.

Post a Comment for "Pass Command Line Argument To Python Script"