Pass command line argument to python script [duplicate]

孤人 提交于 2021-02-04 21:09:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!