最近,被python中的全局变量搞的挺迷惑。
在看openstack的配置文件时,总会看到,在文件头部有一些配置,在/etc/***/*.conf文件也有配置,那么具体哪个生效呢,这就要用到python中全局变量的特性了!
先举例:
flag.py
X="1"
Y="2"
def setx():
global X
X="1.new"
sub.py
import flag
def printy():
print flag.Y
def printx():
print flag.X
main_moudle.py(主程序)
import flag
import sub
flag.setx()
while True:
key=raw_input("input :")
sub.printx()
sub.printy()
结果:
1.new
2
这说明,只要在任意模块中修改了flag中的变量,那么在其他模块中使用时,模块flag中的变量的值也会改变。
这个类似于openstack中的配置:
所有的配置文件都放在flags文件下,服务启动时,调用一下脚本:
import eventlet
eventlet.monkey_patch()
import os
import sys
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(
sys.argv[0]), os.pardir, os.pardir))
if os.path.exists(os.path.join(possible_topdir, "cinder", "__init__.py")):
sys.path.insert(0, possible_topdir)
from cinder import flags #全局变量
from cinder.openstack.common import log as logging
from cinder import service
from cinder import utils
if __name__ == '__main__':
flags.parse_args(sys.argv) #这里从/etc/cinder/cinder.conf中加载了配置文件,修改了flags中的全局变量
logging.setup("cinder")
utils.monkey_patch()
server = service.WSGIService('osapi_volume')
service.serve(server)
service.wait()
那么在cinder其他模块中所调用的flags都是此全局变量
这个也说明了了openstack配置文件的优先级:
/etc下的配置文件中优先,其次是模块中的设置;