简体   繁体   中英

Live detect of variable change

Is it possible to set up a loop with live variable changes? I'm using threading, and the variables can change very often in between lines.

I'm looking for something like this:

length = len(some_list)
while length == len(some_list):
    if check_something(some_list):
        # The variable could change right here for 
        # example, and the next line would still be called.
        do_something(some_list)

So far I've had no luck, is this something that's possible in python?

EDIT: More what I'm looking for is something so that the loop restarts if some_list changes.

If its just a single changing list, you can make a local copy.

def my_worker():
    my_list = some_list[:]
    if check_something(my_list):
        do_something(my_list)

UPDATE

A queue may work for you. The thing that modifies needs to post to the queue, so its not an automatic thing. There is also the risk that the background thread falls behind and processes old stuff or ends up crashing everything if memory is exhausted by the queue.

import threading
import queue
import time

def worker(work_q):
    while True:
        some_list = work_q.get()
        if some_list is None:
            print('exiting')
            return
        print(some_list)

work_q = queue.Queue()
work_thread = threading.Thread(target=worker, args=(work_q,))
work_thread.start()

for i in range(10):
    some_list.append(i)
    work_q.put(some_list[:])
    time.sleep(.2)
work_q.put(None)

work_thread.join()

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