【发布时间】:2019-06-05 08:21:30
【问题描述】:
我有一个简单的程序(如下),它的行为与我预期的不同 我通过 PyCharm 运行它。通过命令提示符运行时,它的行为符合预期。
这是一个产生一个新进程的程序,但之后,它使用input()函数从用户那里读取输入。问题是当我使用这个功能时,直到输入输入,进程才开始。
当我改用threading 模块并创建一个新线程时,不会出现此问题。但我需要使用multiprocessing 模块,因为我在生成的进程中启动 GUI,如果不在单独的进程中而不是在新线程中运行,则会产生其他问题。
我发现的一种解决方法是在调用start() 之后再使用sleep(),但如果我等待 GUI 启动的时间不够长,它可能会因 CPU 功率而失败。
所以我想知道为什么会出现这个问题以及是否有一种优雅的方法来解决它而不是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 上不会发生。
sleep(0)有效吗? -
sleep(0) 不起作用。但我刚刚发现,问题只有在我通过 PyCharm 运行时才会出现。当我在命令提示符下运行它时,它不会发生。我将编辑问题以反映这一点。
-
我无法复制此问题,但您可以尝试将您的
input-handling 包装在一个额外的线程中。
标签: python multithreading input multiprocessing