Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 variable the other one still sees the default value.

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 would print 0 everytime I hope I've made my problem clear, and someone can help me. If you need some more information please feel free to ask.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
573 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

There is no such magic as you are hoping would exist: just as if you have two instances of the same program running, each one will have its instance of variables (global or otherwise).

If you are performing some simple task, the easier way to go is to have one text file as output for each process, and the other process trying to read information from the file generated by each process it wants to know about - (you could even use named pipes in Unixes).

The other way is to have a Python script to coordinate the starting of your daemons using the multiprocessing stdlib module, and then create a multiprocessing.Manager object to share variables directly between process. This can be more complicated to set up at first, but it is the clean thing to do. Check the docs on the Manager class here: https://docs.python.org/3/library/multiprocessing.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...