[英]reading config from file
我嘗試讀取配置文件並將值分配給變量:
#!/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
您的sever
變量是configurebot
函數中的局部變量。
如果你想在函數之外使用它,你必須使它成為global
。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.