cx_Freeze 可执行文件在使用多处理和 freeze_support 时运行多个任务

cx_Freeze executable runs multiple tasks when using multiprocessing and freeze_support

我用 cx_Freeze 构建了一个可执行文件。我总是读到我需要包含 multiprocessing.freeze_support 以避免任务管理器中可执行文件 运行ning 的多个任务。但是如果我使用 multiprocessing 和 freeze_support 我仍然会在任务管理器中得到两个任务 运行ning。

这是我的示例 GUI,名称为 test_wibu.py:

import multiprocessing
from multiprocessing import freeze_support
import threading
import queue
import tkinter as tk
import psutil

import time
from tkinter.filedialog import *
sys._enablelegacywindowsfsencoding()

def worker(pqueue):
    while True:
        obj = pqueue.get()
        obj.execute()
        del obj


if __name__ == '__main__':
    freeze_support()

    q = queue.Queue(maxsize=0)

    root = Tk()


    print('Doing something to build the software interface')
    time.sleep(3)

    label = Label(root, text='Software', anchor=CENTER)
    label.grid(column=0, row=0, sticky='nwse', padx=0, pady=0)

    pqueue = multiprocessing.Queue()

    pool = multiprocessing.Pool(1, worker, (pqueue,))

    parent = psutil.Process()

    q.put('stop')

    root.mainloop()

还有我的 setup_wibu.py:

import os.path
from cx_Freeze import *


PYTHON_INSTALL_DIR = os.path.join(os.getenv('LOCALAPPDATA'), 'Programs', 'Python', 'Python36')
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')


executables = [
    Executable('test_wibu.py',
               base='Win32GUI',
               targetName='test.exe',
               )
]

options = {
    'build_exe': {
        'excludes': ['gtk', 'PyQt4', 'PyQt5', 'scipy.spatial.cKDTree', 'sqlite3', 'IPython'],
        'packages': [],
        'includes':['pkg_resources'],
        'include_files': [os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
                          os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll')]

    },
}

setup(
    name='Pest_wibu',
    version='1.0',
    executables=executables,
    options=options,

)

如果我构建可执行文件并 运行 它,我会在任务管理器的“详细信息”中获得两个名为 test.exe 的任务。 这是正常行为吗?如何避免可执行文件创建多个任务?

根据this excellent answer,调用multiprocessing.freeze_support()的原因是

lack of fork() on Windows (which is not entirely true). Because of this, on Windows the fork is simulated by creating a new process in which code, which on Linux is being run in child process, is being run.

因此如您的前提所述,不要在任务管理器中避免可执行文件 运行 的多个任务。

因此,您在任务管理器中观察到的行为可能是正常的,无法避免。