python - input() 函数阻止新的多处理进程在通过 PyCharm 运行时启动

标签 python multithreading input multiprocessing

我有一个简单的程序(如下),当它的行为不符合我的预期时 我通过 PyCharm 运行它。通过命令提示符运行时,它的行为符合预期。

它是一个生成新进程的程序,但之后使用 input() 函数读取用户的输入。问题是,当我使用此功能时,直到输入输入后该过程才会启动。

当我使用 threading 模块并创建新线程时,不会出现此问题。但我需要使用 multiprocessing 模块,因为我在生成的进程中启动 GUI,如果不在单独的进程中运行而不是在新线程中运行,则会产生其他问题。

我发现的一个解决方法是在调用 start() 之后进行 sleep() ,但这感觉像是一个丑陋的解决方法,如果我不这样做,可能会失败,具体取决于 CPU 功率无需等待 GUI 启动足够长的时间。

所以我想知道为什么会出现这个问题,是否有一种优雅的方法来解决它而不是 sleep()

import multiprocessing as mp
import time


def my_func():
    print("The process has started.")


def main():
    p = mp.Process(target=my_func)
    p.start()

    # If we uncomment this, process will start as expected. If commented out, it will wait for input.
    # time.sleep(1)

    # Things I want to do while the process is on-going like getting an input from user and processing the input.
    print(input("Please input something:"))

    # wait for the window to be closed
    p.join()


if __name__ == '__main__':
    main()

我使用 Windows 10、PyCharm 2019.1、Python 3.6.8、64 位

最佳答案

在 Linux 上不会发生。甚至将多处理 set_start_method 更改为 spawn

您可以粘贴一些屏幕截图或日志吗?

关于python - input() 函数阻止新的多处理进程在通过 PyCharm 运行时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56456695/

相关文章:

python - 使用 Tornado 通过 GET 处理所有 REST 请求

python - 同时运行多个独立的python脚本

Java:使用 Scanner 类从文件中读取输入而无需管道

angular - 如何在Angular 5中实现货币类型输入?

python - 使用 Numpy ndarray 进行条件索引

Python:绘制 3D 曲面时出现 AttributeError

python - Tensorflow:更改深度 CNN 的批量大小时出错

c++ - 使用已删除的函数 'std::thread::thread(const std::thread&)'

Java GUI 线程

c++ - 如何在 Windows 上使用 C++ 访问低级硬件 I/O 函数?