python实现全局变量共享,一个全局变量在多个文件中使用

因为业务需求要将抓到的数据进行累加统计,而且还要间隔三秒钟将这个数据推送到服务端,所以就要实现一个全局变量来记录这个数据,而且推送服务要每隔三秒钟就推送一次到服务端。之前使用了一个全局文件common.py,里面存储这个变量total,然后一个设置total=1000,另一个读total,但是发现读不到修改后的值,不知道问题出在哪里。后来将这个变量设置为一个全局对象的属性,然后再修改这个属性,然后另一个文件中读取这个属性,就好了

基本的目录结构:

common.py用来存储全局变量的:

class Global:
    total = 0
    name = ""

 first.py是用来修改全局变量的:

import threading
import time
from src.common import Global


def add_count():
    while True:
        Global.total += 1
        print(f"add_count开始设置: {Global.total}\n")
        time.sleep(3)


def run():
    print("first run")
    t = threading.Thread(target=add_count)
    t.start()


if __name__ == '__main__':
    run()

second.py是用来读取这个变量的:

import threading
import time
from src.common import Global


def read_count():
    while True:
        print(f"read_count全局变量是:{Global.total}\n")
        time.sleep(3)


def run():
    print("first run")
    t = threading.Thread(target=add_count)
    t.start()


if __name__ == '__main__':
    run()

最后还需要一个main.py,这个是主程序入口,不能单独运行first.py和second.py,因为那样的话, 相当于两个进程,这个并不是两个进程间通讯,所以要保证这两个程序运行在同一进程中,所以就需要使用统一的入口来管理:main.py

import threading
from src.first import add_count
from src.second import read_count


def main():
    print("运行主程序")
    t1 = threading.Thread(target=add_count)
    t2 = threading.Thread(target=read_count)
    t1.start()
    t2.start()


if __name__ == '__main__':
    main()

 最终实现的效果:

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/133043889