将命令行参数传递给 python 脚本 [英] Pass command line argument to python script
本文介绍了将命令行参数传递给 python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 file.py,我想在调用时将 base_url
传递给它,这样 base_url
变量值在运行 python file.py 时可以是动态的base_url='http://google.com'
http://google.com
的值然后可以直接用于 file.py 的执行.
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.
我该怎么做?
谢谢
推荐答案
命令行参数存储在列表 sys.argv
中.sys.argv[0]
是调用的命令的名称.
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]
根据输入格式,base_url_arg
可能需要进一步处理.
Depending on the input format, base_url_arg
might have to be further processed.
这篇关于将命令行参数传递给 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文