Python global variables across multiple files

I have 2 daemons that need to access the same variable. I created a third file for global variables and each daemon can access the variable. But when someone changes this variable, the other still sees the default.

Example:

glob.py

time = 0

      

daemon a:

import datetime
import time
import glob

while(True):
    glob.time = datetime.datetime.now()
    time.sleep(30)

      

daemon b:

import glob

while(True):
    print(glob.time)

      

it will print 0 every time I hope I made my problem clear and someone can help me. If you need more information, please do not hesitate to ask.

+2


source to share


2 answers


It looks like (although you don't explicitly say that) you are running your programs in a completely independent way: two different calls to the Python interpreter.

There is no magic as you'd hope: just as if you had two instances of the same program, each would have its own variable instance (global or different).



If you are doing some simple task, the easiest is to make one text file as output for each process and another process tries to read information from the file created by each process it wants to know about - (you can even use named pipes on Unixes) ...

Another way is to use a Python script to coordinate the launch of your daemons using the multiprocessing

stdlib module , and then create a multiprocessing.Manager object to share variables directly between the process. It might be tricky to set up at first, but it's a clean thing. Check the docs in the Manager class here: https://docs.python.org/3/library/multiprocessing.html

+2


source


How do I share global variables between modules?

The canonical way of exchanging information between modules within the same program is to create a special module (often called config or cfg). Just import the config module into all modules of your application; the module is made available as a global name. Since there is only one instance for each module, any changes made to the module object are 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 running a.py:

python b.py
1
2
3
4
5
6

      

+2


source







All Articles