简体   繁体   中英

Python multiprocessing does nothing

Running from Visual Studio > Python console app... OS is Windows 10.

Below simple code does not work. The window stays up for a few seconds and then closes without printing anything on the window.

Please help me fix this. It's been confusing and as I read from Internet so many people reported this, but I really appreciate if you provide me solution that can work on my environment. Thanks.

import multiprocessing
import sys
import os

def foo():
    print('hello')

if __name__ == '__main__':
    multiprocessing.freeze_support()
    multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

    p = multiprocessing.Process(target=foo)
    p.start()

pythonw.exe is a GUI window, not a console. Where do you expect to see the "hello" you printed? If you want to make sure that the code in another process is actually run, write "hello" to some file, or open a window:

from tkinter import Tk

def foo():
    print('hello')
    t = Tk()
    t.mainloop()

or

from pathlib import Path

def foo():
    Path("some_file.txt").write_text("hello")

Also call p.join() at the end to wait for the process to finish.

Is there a reason for using the "set_executable" function? Try to look at the value of sys.executable is it different from the interpreter you would like to use? if it does, what is the path of the executable you want to use?

Try running it in the cmd using the following command python <path_to_script.py>

import multiprocessing
import sys
import os

def foo():
    print('hello')

if __name__ == '__main__':
    #multiprocessing.freeze_support()
    #multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

    p = multiprocessing.Process(target=foo)
    p.start()

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