进程因PyInstaller-executable陷入循环

发布于 2021-01-29 17:31:42

Python v3.5,Windows 10

我正在使用多个进程,并试图捕获用户输入。搜索所有内容,发现在input()与多个进程一起使用时会发生奇怪的事情。经过8个多小时的尝试,我实施的任何工具均无济于事,我很确定自己做错了,但我一生无法解决。

以下是一个精简的程序,演示了该问题。现在,当我在PyCharm中运行此程序时,它可以正常工作,但是当我pyinstaller用来创建单个可执行文件时,它会失败。

我很确定这与Windows如何从我已阅读的内容中获取标准输入有关。我也尝试过将用户输入变量作为Queue()项目传递给函数,但存在相同的问题。我读过您应该将其放入input()主python进程中,所以我在if__name__ = '__main__':

from multiprocessing import Process
import time


def func_1(duration_1):
    while duration_1 >= 0:
        time.sleep(1)
        print('Duration_1: %d %s' % (duration_1, 's'))
        duration_1 -= 1


def func_2(duration_2):
    while duration_2 >= 0:
        time.sleep(1)
        print('Duration_2: %d %s' % (duration_2, 's'))
        duration_2 -= 1


if __name__ == '__main__':

    # func_1 user input
    while True:
        duration_1 = input('Enter a positive integer.')
        if duration_1.isdigit():
            duration_1 = int(duration_1)
            break
        else:
            print('**Only positive integers accepted**')
            continue

    # func_2 user input
    while True:
        duration_2 = input('Enter a positive integer.')
        if duration_2.isdigit():
            duration_2 = int(duration_2)
            break
        else:
            print('**Only positive integers accepted**')
            continue

    p1 = Process(target=func_1, args=(duration_1,))
    p2 = Process(target=func_2, args=(duration_2,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用multiprocessing.freeze_support() PyInstaller生成Windows可执行文件时需要使用。

    直接从文档中

    multiprocessing.freeze_support()

    添加对冻结使用多处理程序的程序以生成Windows可执行文件的支持。(已经使用py2exe,PyInstaller和cx_Freeze进行了测试。)

    需要在主模块的if name ==’ main ‘行之后立即调用此函数。例如:

    from multiprocessing import Process, freeze_support
    
    def f():
        print('hello world!')
    
    if __name__ == '__main__':
        freeze_support()
        Process(target=f).start()
    

    如果省略了Frozen_support()行,则尝试运行冻结的可执行文件将引发RuntimeError。

    在Windows以外的任何操作系统上调用freeze_support()均无效。另外,如果该模块由Windows上的Python解释器正常运行(该程序尚未冻结),则freeze_support()无效。

    在您的示例中,您还应该处理不必要的代码重复。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看