use*_*258 5 python qt ipython multiprocessing
我正在iPython中运行以下代码:
import multiprocessing
def my_function(x):
"""The function you want to compute in parallel."""
x += 1
return x
if __name__ == '__main__':
pool = multiprocessing.Pool()
results = pool.map(my_function, [1,2,3,4,5,6])
print(results)
Run Code Online (Sandbox Code Playgroud)
在Windows的ipython QT控制台中。但是,代码不起作用-QT控制台冻结了。这个问题是特定于iPython的(上面的代码应适用于常规Python 2.7)。
有什么解决办法吗?
至少在当前版本的 Jupyter Notebook(IPython 的继任者)中,您可以通过将目标函数移动到一个单独的模块并导入它来解决这个问题。
我不知道为什么会这样,这很奇怪,但确实如此。
即 - 在workers.py文件中放入
def my_function(x):
"""The function you want to compute in parallel."""
x += 1
return x
Run Code Online (Sandbox Code Playgroud)
然后在 IPython/Jupyter 笔记本中输入:
import multiprocessing
import workers
pool = multiprocessing.Pool()
results = pool.map(workers.my_function, [1,2,3,4,5,6])
print(results)
Run Code Online (Sandbox Code Playgroud)
此外 - 似乎不需要 if-main 东西。