Python 如何从程序中的任何位置访问和修改configparser?
ini数据对于我的python应用程序至关重要。 configparser阵列/数据在全局范围内不可用Python 如何从程序中的任何位置访问和修改configparser?,python,configparser,Python,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 = c
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()
这回答了你的问题吗@MikeScottly谢谢你,但我没有正确实施,我用一个干净的例子更新了我的问题,你能告诉我吗?