简体   繁体   中英

Python: how to share a variable between two modules

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.

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

No, config.flag will not be shared between Test1.py and Test2.py. Test1.py and Test2.py will be running on separate instances of the Python interpreter. Each interpreting loads config.py into it's own parcel of memory.

One option is to use threading to run Test1.py and Test2.py on the same Python instance.

Another option is to store and continuously load the value from the disk, perhaps by saving it in a text file or maybe using SQLite .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM