簡體   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