Jython - importing a text file to assign global variables

雨燕双飞 提交于 2019-12-13 05:52:39

问题


I am using Jython and wish to import a text file that contains many configuration values such as:

QManager = MYQM
ProdDBName = MYDATABASE

etc.

.. and then I am reading the file line by line.

What I am unable to figure out is now that as I read each line and have assigned whatever is before the = sign to a local loop variable named MYVAR and assigned whatever is after the = sign to a local loop variable MYVAL - how do I ensure that once the loop finishes I have a bunch of global variables such as QManager & ProdDBName etc.

I've been working on this for days - I really hope someone can help.

Many thanks, Bret.


回答1:


See other question: Properties file in python (similar to Java Properties)

Automatically setting global variables is not a good idea for me. I would prefer global ConfigParser object or dictionary. If your config file is similar to Windows .ini files then you can read it and set some global variables with something like:

def read_conf():
    global QManager
    import ConfigParser
    conf = ConfigParser.ConfigParser()
    conf.read('my.conf')
    QManager = conf.get('QM', 'QManager')
    print('Conf option QManager: [%s]' % (QManager))

(this assumes you have [QM] section in your my.conf config file)

If you want to parse config file without help of ConfigParser or similar module then try:

my_options = {}
f = open('my.conf')
for line in f:
    if '=' in line:
        k, v = line.split('=', 1)
        k = k.strip()
        v = v.strip()
        print('debug [%s]:[%s]' % (k, v))
        my_options[k] = v
f.close()
print('-' * 20)
# this will show just read value
print('Option QManager: [%s]' % (my_options['QManager']))
# this will fail with KeyError exception
# you must be aware of non-existing values or values
# where case differs
print('Option qmanager: [%s]' % (my_options['qmanager']))


来源:https://stackoverflow.com/questions/16207141/jython-importing-a-text-file-to-assign-global-variables

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