从文件中读取配置

时间:2012-05-04 18:14:37

标签: python file config

我尝试读取配置文件并将值分配给变量:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


with open('bot.conf', 'r') as bot_conf:
    config_bot = bot_conf.readlines()
bot_conf.close()

with open('tweets.conf', 'r') as tweets_conf:
    config_tweets = tweets_conf.readlines()
tweets_conf.close()

def configurebot():
    for line in config_bot:
        line = line.rstrip().split(':')
    if (line[0]=="HOST"):
        print "Working If Condition"
        print line
        server = line[1]


configurebot()
print server

它似乎做得很好,除了它没有为服务器变量赋值

ck@hoygrail ~/GIT/pptweets2irc $ ./testbot.py 
Working If Condition
['HOST', 'irc.piratpartiet.se']
Traceback (most recent call last):
  File "./testbot.py", line 23, in <module>
    print server
NameError: name 'server' is not defined

2 个答案:

答案 0 :(得分:1)

sever变量是configurebot函数中的局部变量。

如果你想在函数之外使用它,你必须使它global

答案 1 :(得分:1)

server符号未在您使用它的范围内定义。

为了能够打印它,您应该从configurebot()返回。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


with open('bot.conf', 'r') as bot_conf:
    config_bot = bot_conf.readlines()
bot_conf.close()

with open('tweets.conf', 'r') as tweets_conf:
    config_tweets = tweets_conf.readlines()
tweets_conf.close()

def configurebot():
    for line in config_bot:
        line = line.rstrip().split(':')
    if (line[0]=="HOST"):
        print "Working If Condition"
        print line
        return line[1]


print configurebot()

您也可以通过在调用configurebot()之前声明它来使其全局化:

server = None
configurebot()
print server