Jython-导入文本文件以分配全局变量 [英] Jython - importing a text file to assign global variables
问题描述
我正在使用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屋!