问题
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
回答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
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.
回答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.
来源:https://stackoverflow.com/questions/50193084/pass-command-line-argument-to-python-script