How to print results of Python ThreadPoolExecutor.map immediately?

2024/9/20 22:58:14

I am running a function for several sets of iterables, returning a list of all results as soon as all processes are finished.

def fct(variable1, variable2):# do an operation that does not necessarily take the same amount of# time for different input variables and yields result1 and result2return result1, result2variables1 = [1,2,3,4]
variables2 = [7,8,9,0]with ThreadPoolExecutor(max_workers = 8) as executor:future = executor.map(fct,variables1,variables2)print '[%s]' % ', '.join(map(str, future))

>>> [ (12,3) , (13,4) , (14,5) , (15,6) ]

How can I print intermediary results e.g. for variable1 = 1, variable2 = 7 as soon as their results are calculated?

Answer

If you want to consume the results as they finish without preserving the order of the original iterable, you can use executor.submit along with concurrent.futures.as_completed:

from concurrent.futures import ThreadPoolExecutor, as_completed
import time
import randomdef fct(variable1, variable2):time.sleep(random.randint(1,5))return variable1+1, variable2+1variables1 = [1,2,3,4]
variables2 = [7,8,9,0]with ThreadPoolExecutor(max_workers = 8) as executor:for out in as_completed([executor.submit(fct,*vars) for vars in zip(variables1, variables2)]):print(out.result())

Output (though any order is possible on any given run, due to random.randint):

(4, 10)
(5, 1)
(2, 8)
(3, 9)

as_completed will yield a Future from its input list as soon as that Future is marked as done, regardless of where it actually falls in the input list. This way, if the second item is done after 2 seconds, but the first takes fifteen, you'll see the result of the second items after two seconds, rather than needing to wait fifteen. This may or may not be desirable behavior, depending on your specific use-case.

Edit:

Note that you can still get the output in the original order this way. You just need to save the list you give to as_completed:

with ThreadPoolExecutor(max_workers = 8) as executor:jobs = [executor.submit(fct, *vars) for vars in zip(variables1, variables2)]for out in as_completed(jobs):print(out.result())results = [r.result() for r in jobs]print(results)

Output:

(5, 1)
(2, 8)
(3, 9)
(4, 10)
[(2, 8), (3, 9), (4, 10), (5, 1)]
https://en.xdnf.cn/q/72450.html

Related Q&A

Python dir equivalent in perl?

The dir command in Python 2.7.x lists all accessible symbols from a module. Is there an equivalent in Perl 5.x to list all accessible symbols from a package?

Entire JSON into One SQLite Field with Python

I have what is likely an easy question. Im trying to pull a JSON from an online source, and store it in a SQLite table. In addition to storing the data in a rich table, corresponding to the many fiel…

Python scipy module import error due to missing ._ufuncs dll

I have some troubles with sub-module integrate from scipy in python. I have a 64 bits architecture, and it seems, according to the first lines of the python interpreter (see below) that I am also using…

How can I call python program from VBA?

Just as the title goes.I have a python program which processes some data file I downloaded from email.I am writing a vba script which can download the email attachments and execute the python program t…

Embedding CPython: how do you constuct Python callables to wrap C callback pointers?

Suppose I am embedding the CPython interpreter into a larger program, written in C. The C component of the program occasionally needs to call functions written in Python, supplying callback functions …

python - beautifulsoup - TypeError: sequence item 0: expected string, Tag found

Im using beautifulsoup to extract images and links from a html string. It all works perfectly fine, however with some links that have a tag in the link contents it is throwing an error.Example Link:<…

Python evdev detect device unplugged

Im using the great "evdev" library to listen to a USB barcode reader input and I need to detect if the device suddenly gets unplugged/unresponsive because otherwise the python script reading …

python: urllib2 using different network interface

I have the following code:f = urllib2.urlopen(url) data = f.read() f.close()Its running on a machine with two network interfaces. Id like to specify which interface I want the code to use. Specifically…

RuntimeError: as_numpy_iterator() is not supported while tracing functions

while i was using function as_numpy_iterator() got error--------------------------------------------------------------------------- RuntimeError Traceback (most recent call…

Pandas assert_frame_equal error

Im building test cases and I want to compare 2 dataframes. Even though dataframe have the same columns and values assert_frame_equal reports are not equal. Column order is different, I tried reordering…