Jython-导入文本文件以分配全局变量 [英] Jython - importing a text file to assign global variables

查看:79
本文介绍了Jython-导入文本文件以分配全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jython,并希望导入一个包含许多配置值的文本文件,例如:

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

QManager = MYQM
ProdDBName = MYDATABASE

..然后我逐行读取文件.

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

我现在无法弄清的是,当我阅读每一行并已将=符号之前的内容分配给名为MYVAR的局部循环变量,并将=符号之后的内容分配给了局部循环变量MYVAL-如何确保一旦循环结束,我就会有一堆全局变量,例如QManager& ProdDBName

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.

非常感谢, 布雷特.

推荐答案

查看其他问题:

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

自动设置全局变量对我来说不是一个好主意.我更喜欢全局ConfigParser对象或字典.如果您的配置文件与Windows .ini文件相似,则可以读取它并设置一些全局变量,例如:

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))

(假设您在my.conf配置文件中有[QM]部分)

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

如果要在没有ConfigParser或类似模块帮助的情况下解析配置文件,请尝试:

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']))

这篇关于Jython-导入文本文件以分配全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆