简体   繁体   中英

reading config from file

I try to read a config file and assign the values to variables:

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

it seems to do all fine except it doesn't assign any value to the server variable

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

your sever variable is a local variable in the configurebot function.

if you want to use it outside of the function, you must make it global .

server symbol is not define in the scope you use it.

To be able to print it, you should return it from 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()

You can also make it global by declaring it before the call to configurebot() as followed:

server = None
configurebot()
print server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM