我尝试读取配置文件并将值分配给变量:
#!/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
答案 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