繁体   English   中英

python - 如何在 memory 中存储设置?

[英]python - how to store settings in memory?

我是 Python 的新手,我正在尝试找出一种存储设置的方法。 我的应用程序(python + pyqt5)将设置存储在 SqLite 数据库中。 function 在启动时加载这些设置并相应地设置所有文本框和复选框。

根据设置,我的程序确实必须做出不同的反应。 我的程序在多个线程上工作,所有这些线程都需要知道相关设置。 我不想每次需要设置时都访问 UI,我希望将值存储在一个变量中,并让整个应用程序都可以访问该变量。 (只读就够了...)

现在,这就是我在脑海中看到的,但现在我想知道这是否有意义,如果有不同的方法,那更好,如果有类似“全局环境变量”的东西可以从任何地方读取?

我在网上搜索过,但没有找到这方面的任何信息。

到目前为止我探索了哪些选项:

  • 将值传递给线程,以便它们拥有自己的设置“副本”。 这不起作用,因为某些功能等待外部输入,并且当它们使用设置时,它们可能已被更改并且已经过时。

  • 与上面相同,但每次发生变化时都会使用专用信号更新设置。 有效,但有重新发明轮子的感觉。 必须有更好的方法。

  • 从任何地方制作一个全局变量 accessibel - 会很好,但到目前为止找不到方法来做到这一点。

  • 在需要时从每个线程查询数据库。 有效,但我不喜欢它。 感觉比直接访问 memory 慢。

您可以在主线程中定义一个“环境”object,并将其传递给所有线程/任务。 例如:

from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from random import randint

@dataclass
class MyEnv():
    mynumber : int = 0

def setup_task(env):
    env.mynumber = randint(0,10)
    return(f'setting the magic number to {env.mynumber}')

def normal_task(env):
    return(f'the magic number is currently {env.mynumber}')

myenv = MyEnv()

with ThreadPoolExecutor(10) as executor:
        for future in [executor.submit(task, myenv) for i in range(10) for task in [setup_task, normal_task]]:
            print(future.result())
----
setting the magic number to 1
the magic number is currently 1
setting the magic number to 1
the magic number is currently 1
setting the magic number to 9
the magic number is currently 9
setting the magic number to 3
the magic number is currently 3
setting the magic number to 4
the magic number is currently 4
setting the magic number to 0
the magic number is currently 0
setting the magic number to 8
the magic number is currently 8
setting the magic number to 2
the magic number is currently 2
setting the magic number to 1
the magic number is currently 1
setting the magic number to 10
the magic number is currently 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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