Good day. I need advice, as one thread, to take data from another while it is being executed. (A bit clumsily, I did not invent a better wording.)

While it looks like this:

import sys import threading import time #Тут можно не смотреть, готовая рабочая функция!!! # Print iterations progress def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r') # Print New Line on Complete if iteration == total: print() #Тут начинаем смотреть, начинается мой быдлокод! def long_function(): # некая функция, которая выполняется какое-то время, # по времени она не однородна n=0 while n<10: if n<3: time.sleep(2) else: if n<8: time.sleep(3) else: if n<11: time.sleep(1) n=n+1 return n # собственно какой-то способ как отдавать на каждой итерации переменную l = 10 t = threading.Thread(target=long_function) t.start() printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50) while t.is_alive(): # пока функция выполняется t.join(1) # f = long_function естественно это не работае. printProgressBar(f + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50) 

Meaning, there is a certain function, it is somehow executed, I want to track its progress in the future. Naryl in the open spaces, a way to implement progress.

The question is how do I place data from the function being executed in a separate thread into the variable f (while it is being executed and not when it ends)

    4 answers 4

     import queue import threading import time def long_function(q): # некая функция, которая выполняется какое-то время, n=0 while n<10: if n<3: time.sleep(2) else: if n<8: time.sleep(3) else: if n<11: time.sleep(1) n=n+1 q.put_nowait(n) # собственно какой-то способ как отдавать на каждой итерации переменную qe = queue.Queue() t = threading.Thread(target=long_function, args=[qe]) t.start() while t.is_alive(): # пока функция выполняется n = qe.get() print(n) 
    • can be easier: for n in iter(q.get, None): print(n) and at the end of long_function() : q.put(None) . - jfs
    • Thanks, earned and additionally figured out the queue. - Nick Su

    In addition to the queue ( queue.Queue ), to bind the producer / consumer streams, you can send a callback:

     def f(on_update): while True: ... on_update(n) 

    An example from stdlib: urlretrieve() takes the reporthook function:

     with TqdmUpTo(unit='B', unit_scale=True, desc=filename, miniters=1) as t: urlretrieve(url, filename=filename, reporthook=t.update_to) 

    where the TqdmUpTo class is defined in the documentation of the tqdm module .

    download-progressbar-tqdm.py's tty session

    Another example of the reporthook functions that implement the text interface / tkinter GUI, with threads / without threads .

      well, for example, declare n global in function

       def long_function(): # некая функция, которая выполняется какое-то время, # по времени она не однородна global n .... 

      return n accordingly is not necessary.

      the progress bar call will be

       printProgressBar(n, l, prefix = 'Progress:', suffix = 'Complete', length = 50) 

        It is better not to use threading because it is not multithreading, but slag is incomprehensible.

         import time import multiprocessing def worker(status): for i in range(10): time.sleep(2) status.value = i status = multiprocessing.Value('i') process = multiprocessing.Process(target=worker, args=(status,)) process.start() while process.is_alive(): time.sleep(1) print(status.value) 
        • one
          minus for an incomprehensible slag :), sort out when it’s worth using threading to bring acceleration - vadim vaduxa
        • with threading everything is ok, if you want to do I / O inside threads. For example, in connection-pools to the database. In general, the use of multiprocessing here can be good advice if there is a lot of computation in the thread. And GIL doesn't hurt to read the comment author, of course: wiki.python.org/moin/GlobalInterpreterLock - dred