在 jupyter notebook 中运行代码时 BrokenProcessPool

问题描述:

我正在学习 Python 中的多处理.我有以下代码片段:

I am learning about multiprocessing in python. I have the following code snippet:

import time
import concurrent.futures

def wait(seconds):
    print(f'Waiting {seconds} seconds...')
    time.sleep(seconds)
    return f'Done'

if __name__ == "__main__":
    with concurrent.futures.ProcessPoolExecutor() as executor:
        p = executor.submit(wait,1)
        print(p.result())

运行它给我这个错误:

BrokenProcessPool                         Traceback (most recent call last)
<ipython-input-19-8eff57e3a077> in <module>
      9     with concurrent.futures.ProcessPoolExecutor() as executor:
     10         p = executor.submit(do_something,1)
---> 11         print(p.result())

~\.conda\envs\w\lib\concurrent\futures\_base.py in result(self, timeout)
    433                 raise CancelledError()
    434             elif self._state == FINISHED:
--> 435                 return self.__get_result()
    436             else:
    437                 raise TimeoutError()

~\.conda\envs\w\lib\concurrent\futures\_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

我使用的是 Windows 计算机,并且在我的代码中使用了 if __name__ == "__main__":.但我仍然收到此错误.

I am on a Windows computer and I have used if __name__ == "__main__": in my code. But I still get this error.

我开始工作了!我将 wait 函数保存在一个名为 wait.py 的单独 python 文件中,并将其导入到 jupyter notebook 中.

I got it to work! I saved the wait function in a separate python file called wait.py and imported it in jupyter notebook.

wait.py:

import time

def wait(seconds):
    print(f'Waiting {seconds} seconds...')
    time.sleep(seconds)
    return f'Done'

ipynb 文件:

import concurrent.futures
import wait

if __name__ == "__main__":
    with concurrent.futures.ProcessPoolExecutor() as executor:
        p = executor.submit(wait.wait,1)
        print(p.result())