如何解决如何从程序中的任何位置访问和修改configparser?
.ini数据对我的python应用程序至关重要。 configparser数组/数据在全球不可用
import configparser
def write_config():
config = configparser.ConfigParser()
with open('config.ini','w') as configfile:
config.write(configfile)
def read_config():
config = configparser.ConfigParser()
config.sections()
config.read('config.ini')
# things are fine here
print(config['DEFAULT']['G'])
read_config()
#here,or from other functions,I cannot access or modify config like
print(config['DEFAULT']['G'])
#I would also like to change config anywhere in app
config['DEFAULT']['G']="100"
#then just call write_config
write_config()
使我的方式(带有功能)工作的正确方法是什么? 我确实意识到,跳过这些功能并使程序平坦将可以解决该问题。 我确实知道如何使变量成为全局变量,但是我显然无法在函数/外部库中使变量成为全局变量
解决方法
这有效:我不确定这是100%正确的方法。
import configparser
config=[]
def write_config():
global config
print("before")
print(config['DEFAULT']['G'])
#config = configparser.ConfigParser()
print("after")
print(config['DEFAULT']['G'])
#config['DEFAULT']['R']="34"
#config['DEFAULT']['G']="52"
with open('config.ini','w') as configfile:
config.write(configfile)
def read_config():
global config
config = configparser.ConfigParser()
config.sections()
config.read('config.ini')
#write_config()
read_config()
print("here,or other functions,I cannot access or modify config")
print(config['DEFAULT']['G']) #does not work.
#I would also like to change config anywhere in app
config['DEFAULT']['G']="100"
#then just call write_config
write_config()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。