Jakub Jakub - 3 months ago 8
Python Question

How to access a variable being updated in a while loop

I am trying to access a variable that is being constantly updated in a while loop in a different file. Here is the code I used for testing:

# file1
import time
x = 0
while True:
x += 1
time.sleep(2.0)

# file2
from file1 import x
print x


When I run file2, it starts the while loop from the beginning. I would like to access one instance of x. For example, if x=10, I would want file2 to print 10. Is this possible?

Answer

You can try the following. First, as there's and infinite loop, importing file1 will block, so you should run the loop in a thread. And second you can wrap the integer being incremented in a list (or any other kind of objects), so you can use the reference to its current value (otherwise you will be importing a value not a reference):

# file1    
import time
import threading

x = [0]

def update_var(var):
    while True:
        var[0] += 1
        time.sleep(2.0)

threading.Thread(target=update_var, args=(x,)).start()

# file2
from file1 import x
print x[0]