Python:共享值总是0

2024-06-26 13:51:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在两个python脚本之间共享一个值,在第一个脚本处使用单例设置值,但是在第二个脚本处获取值时,将返回默认值(0)。你知道吗

这是我的档案: 获取值的文件:

import mod #import the singleton class

...

    def sendDistance(self):

        print(mod.getDistance()) #get the value

设置值的文件:

 import mod #import the singleton class
 ...


    mod.setDistance(35) #set the value with the singleton file mod.py

单例文件:(平日)你知道吗

import distance #import the file where value is stored
def setDistance(val): #set Value function
    distance.x=val
def getDistance(): #get value function
    return distance.x

以及存储值的文件:(距离.py)你知道吗

x=0 #the default value that should be modified from mod

如果我尝试在设置值的文件中获取值(打印(mod.getValue模块())),则正确显示值。 但是在getter端,值总是0。你知道吗


Tags: 文件theimport脚本modgetvaluedef
1条回答
网友
1楼 · 发布于 2024-06-26 13:51:44

设置距离只会在Python的运行实例中设置它。 当然,您可以用新值重写distance.py。 但当其他脚本导入该模块时,这只会影响其他脚本。你知道吗

如果您想在不同时间但在同一台机器上运行的脚本之间共享数据,只需将该数据写入一个文件。使用容易解析的格式,比如JSON。你知道吗

在同时运行的不同脚本之间共享数据更为复杂。最简单的方法是让一个脚本启动另一个脚本。然后可以使用multiprocessing模块的通信特性。你知道吗

为了在可能在不同机器上运行的脚本之间共享数据,可以使用socket模块。你知道吗

相关问题 更多 >