Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to share a variable between two modules

Tags:

python

I have viewed some other threads that address the problem but not quite get it.

Suppose I have a config file that contains a shared variable:

Config.py

flag = False

Test1.py

import config
while(1):
    config.flag = True
    print config.flag

Test2.py

import config
while(1):
    config.flag = False
    print config.flag

If now I run Test1.py and Test2.py, can I see the switch between 'True' 'False' in the output? I don't care about synchronization at this point, as long as it can access the shared variable, then it's done.

Thanks.

like image 867
Chen Xie Avatar asked May 10 '26 16:05

Chen Xie


1 Answers

No. As long as you're running both instances in separate processes, memory won't be magically shared.

You're starting two different (Python) processes. Those processes import the config module. Simplified, this is just a form of loading the code in config.py. There is no further communication going between the processes.

(As a side note, the code in config.py is only interpreted the first time, it's compiled and saved in a separate config.pyc which loads much faster. The next time config.py is edited, config.pyc will be recreated).

There are other options:

  • Use threads
  • Use some other form of memory sharing, for example pipes.

Example with threads:

config.py

flag = False

test.py

import thread
import time

import config


def test1():
    while 1:
        config.flag = True
        time.sleep(0.7)
        print 'test1:', config.flag
        time.sleep(1)

def test2():
    while 1:
        config.flag = False
        time.sleep(1.1)
        print 'test2:', config.flag
        time.sleep(1)

thread.start_new(test1, ())
test2()

It may be helpful to post the reason you're trying to do this. Multithreading is a difficult topic. This question may be useful: https://stackoverflow.com/questions/4690518/multithreading-in-python

like image 97
ayke Avatar answered May 12 '26 07:05

ayke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!