从fi读取配置

2024-10-04 11:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

它似乎做得很好,只是它没有给服务器变量赋值

^{pr2}$

Tags: configcloseserverusrconfasbot配置文件
2条回答

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()之前声明它来使其全局化,如下所示:

^{pr2}$

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

如果要在函数之外使用它,必须使它^{}。在

相关问题 更多 >