问题描述
目前我的包中有 config.py
,我可以从其他 py 文件访问 config.py 中定义的变量,如
Currently I have config.py
in my package and I can access variables defined in config.py from other py files as
import config
var1 = config.var1
首先,我可以将文件作为参数传递吗?test.py config.py
First of all, Can I pass file as argument?test.py config.py
但是有没有办法通过命令行将配置文件作为参数传递并访问其中定义的变量?我看到有 sys
模块来获取通过命令行传递的参数.但是我可以在传递的文件中获取定义的变量吗?
But is there way to pass config file through command line as argument and access the variables defined in it? I see there is sys
module to get arguments passed through command line. But can I get variables defined in passed file?
编辑现在我可以以 __import__(sys.argv[1])
的形式访问传递文件中的变量,并调用 python test.py config
.但是我可以通过提供 pythonpath 来调用 config.py 文件吗?e/g/python test.py ~/Desktop/config
还是 PYTHONPATH='~/Desktop/' python test.py config
?因为如果我这样做,我会得到没有模块错误
.
editNow I am able to access variables in passed file as __import__(sys.argv[1])
and called python test.py config
. But can I call config.py file by giving pythonpath? e/g/ python test.py ~/Desktop/config
or PYTHONPATH='~/Desktop/' python test.py config
? Because if I do this I get no module error
.
推荐答案
您使用 import config
所做的是使 config.py
中的所有名称都可以在您的脚本中使用.
What you do with import config
is make all names from config.py
available in your script.
您可以使用 __import__(sys.args[1])
来做到这一点,如 这个问题.
You can do this using __import__(sys.args[1])
like stated in answers to this question.
但是对于实际的程序配置,请务必查看 argparse
模块!
But for actual program configuration, sure do take a look at the argparse
module!
p = argparse.ArgumentParser(description="...")
p.add_argument("--var1", type=int)
p.add_argument("--var2", type=str)
config = p.parse_args() # will look at sys.args by default
if config.var1 > 10:
....
这篇关于如何从通过命令行传递的文件中访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!