0

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

#!/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
4

2 回答 2

1

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

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

于 2012-05-04T18:17:54.750 回答
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
于 2012-05-04T18:18:07.713 回答