简体   繁体   English

Python 多处理什么也不做

[英]Python multiprocessing does nothing

Running from Visual Studio > Python console app... OS is Windows 10.从 Visual Studio > Python 控制台应用程序运行...操作系统是 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. window 会停留几秒钟,然后关闭,不会在 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.这一直令人困惑,当我从 Internet 上看到很多人报告了这一点时,如果您提供可以在我的环境中工作的解决方案,我真的很感激。 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. pythonw.exe是 GUI window,而不是控制台。 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:如果您想确保另一个进程中的代码实际运行,请将“hello”写入某个文件,或打开 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.最后还要调用p.join()以等待该过程完成。

Is there a reason for using the "set_executable" function?是否有使用“set_executable”function 的理由? Try to look at the value of sys.executable is it different from the interpreter you would like to use?尝试查看sys.executable的值与您要使用的解释器不同吗? 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>尝试使用以下命令python <path_to_script.py>cmd中运行它

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM