我正在创建一个类来设置、保存和访问整个项目中的数据.下面是我的数据类:

class Data:
    """This class stores project-related constants as class attributes for easy access throughout the project."""
    ORG_URL: str = "https://www.myurl.com/"
    PROJECT_NAME: str = "My Project"
    root_path: str = ""

    @classmethod
    def set_root_path(cls, new_path):
        cls.root_path = new_path

下面是我的主类,它在运行时设置根:

from multiprocessing import Process, Manager


class Main:
    def __init__(self) -> None:
        # determine if application is a script file or frozen exe
        if getattr(sys, 'frozen', False):
            application_path = os.path.dirname(sys.executable)
        elif __file__:
            application_path = os.path.dirname(__file__)

        data = Data()
        data.set_root_path(f"{application_path}")
        

        with Manager() as manager:
            q = manager.Queue()
            args = manager.Queue()
            print(data.root_path)                          ## prints correct path
            gui = Process(target=GUI,args=(q,args,data))
            runner = Process(target=Runner,args=(q,args,data))
            gui.start()
            runner.start()
            gui.join()
            runner.join()

if __name__ == "__main__":
    Main()

下面是我的Runner类,我在其中访问根路径:

class Runner:
    def __init__(self,q,args,data) -> None:
        print("Initiating Runner")
        self.q = q
        self.args = args
        self.data = data
        print(self.data.root_path)  # prints ''

我try 了多种方法,但都不能解决问题.请帮帮忙.

推荐答案

这是因为在Windows(默认情况下是MacOS)中,进程是spawned,而不是派生的.因此,当产生新的进程时,模块被重新加载,因此模块级别class语句被重新执行,内部类变量的初始化也被重新执行.

要跨进程传输对象,应该使用类的实例,而不是类.为了提高可读性,您可以改为创建一个dataclass:

from dataclasses import dataclass

@dataclass
class Data:
    ORG_URL: str = "https://www.myurl.com/"
    PROJECT_NAME: str = "My Project"
    root_path: str = ""

    def set_root_path(self, new_path):
        self.root_path = new_path

DEMO(在Linux下以显式繁殖模式运行):https://replit.com/@blhsing1/RequiredDisguisedCodewarrior

Python相关问答推荐

使用SKLearn KMeans和外部生成的相关矩阵

Inquirer库不适用于Pyterfly

如何修复fpdf中的线路出血

try 使用tensorFlow.keras.models时optree Import错误

使用Python和PRNG(不是梅森龙卷风)有效地生成伪随机浮点数在[0,1)中均匀?

为什么基于条件的过滤会导致pandas中的空数据框架?

如何在超时的情况下同步运行Matplolib服务器端?该过程随机挂起

如何使用Selenium访问svg对象内部的元素

由于瓶颈,Python代码执行太慢-寻求性能优化

有条件地采样我的大型DF的最有效方法

添加包含中具有任何值的其他列的计数的列

如何检测背景有噪的图像中的正方形

查找两极rame中组之间的所有差异

scikit-learn导入无法导入名称METRIC_MAPPING64'

在Python中管理打开对话框

根据二元组列表在pandas中创建新列

在Python中动态计算范围

梯度下降:简化要素集的运行时间比原始要素集长

在单次扫描中创建列表

未调用自定义JSON编码器