Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function does not print in multiprocessing

I have this code that runs a multi-processing function.

In this code, the function do_something sleeps and prints stuff.

It does sleep (good)

but it does not print anything (bad)

What is wrong and how to fix that?

Thanks

Here is the code:

import concurrent.futures
import time

start = time.perf_counter()

def do_something(seconds):
    print(f"Sleeping {seconds} second(s)...")
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

def main():    
    with concurrent.futures.ProcessPoolExecutor() as executor:
        secs = [5, 4, 3, 2, 1]
        results = executor.map(do_something, secs)
        
        for result in results:
             print(result)
    
    finish = time.perf_counter()
    
    print(f'Finished in {round(finish-start, 2)} second(s)')

if __name__ == "__main__":
    main()
else:
    print("run from import")

Here are my results:

runfile('G:/OneDrive/__PhD/Research/01-BasicModel/43.py', wdir='G:/OneDrive/__PhD/Research/01-BasicModel')
Done Sleeping...5
Done Sleeping...4
Done Sleeping...3
Done Sleeping...2
Done Sleeping...1
Finished in 5.24 second(s)

There is no Sleeping {seconds} second(s)...

P.S. OS = Windows 10 Editor : Spyder

like image 919
asmgx Avatar asked Sep 24 '26 06:09

asmgx


1 Answers

This is a side effect of your editor. The processes are apparently not inheriting the special stdout that redirects to your editor. When I run your code from a command line, I get:

run from import
run from import
run from import
run from import
Sleeping 1 second(s)...
run from import
Sleeping 2 second(s)...
run from import
Sleeping 3 second(s)...
run from import
Sleeping 4 second(s)...
run from import
Sleeping 5 second(s)...
Done Sleeping...5
Done Sleeping...4
Done Sleeping...3
Done Sleeping...2
Done Sleeping...1
Finished in 5.29 second(s)
like image 160
Tim Roberts Avatar answered Sep 25 '26 19:09

Tim Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!