Python Global Variables in multiple files

前端 未结 2 564
醉酒成梦
醉酒成梦 2020-12-02 03:00

I have 2 daemons, which should access the same Variable. I\'ve created a 3rd file for global variables and each daemon can access the variable. But when one changes the var

2条回答
  •  感情败类
    2020-12-02 03:03

    How do I share global variables across modules?

    The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.:

    import time
    import glb
    
    while(True):
        glb.t +=  1
        time.sleep(3)
        print glb.t 
    

    b.py:

    import glb
    import a
    while(True):
        print(glb.t)
    

    glb.py:

    t = 0
    

    Output after starting a.py:

    python b.py
    1
    2
    3
    4
    5
    6
    

提交回复
热议问题