Python implements global variable sharing. A global variable is used in multiple files.

Because the business needs to accumulate the captured data and push this data to the server every three seconds, a global variable must be implemented to record this data, and the push service must be updated every three seconds. Push once to the server. Previously, I used a global file common.py to store the variable total. Then one set total=1000 and the other read total. However, I found that the modified value could not be read. I don’t know where the problem lies. Later, set this variable as a property of a global object, then modify this property, and then read this property from another file, and it will be fine.

Basic directory structure:

common.py is used to store global variables:

class Global:
    total = 0
    name = ""

 first.py is used to modify global variables:

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 is used to read this variable:

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()

Finally, you need a main.py, which is the main program entry. You cannot run first.py and second.py separately, because in that case, it is equivalent to two processes. This is not communication between two processes, so you must ensure that these two The program runs in the same process, so it needs to be managed using a unified entry: 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()

 The final effect achieved:

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/133043889