我有一个简单的程序(如下),当它的行为不符合我的预期时 我通过 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/