1

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 http://google.com could then be used directly in the execution of file.py.

How might I go about doing this?

Thanks

John
  • 155
  • 4
  • 16
  • Asked and answered here: https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments – dstandish May 05 '18 at 19:09

2 Answers2

2

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

if len(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.

piripiri
  • 1,925
  • 2
  • 18
  • 35
0

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.

fferri
  • 18,285
  • 5
  • 46
  • 95