Jupyter == 4.1.0,Python == 2.7.10,IPython == 4.2.0
我正在为我的Jupyter笔记本编写一个SQL UI,并希望结合多线程,以便我可以在一个单元格中运行查询,并在查询运行时继续在其他单元格中工作.
我遇到的问题是,如果我在一个单元格中执行查询,输出将显示在最后执行的单元格的输出提示中,而不是在执行查询的单元格的输出提示中.
我仔细检查了网络,发现了这个聪明的伎俩,但我认为它已经过时了和/或在我的Jupyter版本中不再适用.当我运行它时,我只获得上次执行的任何单元格的输出.因此,如果我同时运行两者,我只获得最后执行的输出,而不是输出打印以同时分离单元格.
所以我有我的上下文管理器设置parent_header:
import sys
import threading
from contextlib import contextmanager
# we need a lock, so that other threads don't snatch control
# while we have set a temporary parent
stdout_lock = threading.Lock()
@contextmanager
def set_stdout_parent(parent):
"""a context manager for setting a particular parent for sys.stdout
the parent determines the destination cell of output
"""
save_parent = sys.stdout.parent_header
with stdout_lock:
sys.stdout.parent_header = parent
try:
yield
finally: …Run Code Online (Sandbox Code Playgroud) 我定义了一个运行 bash 脚本的 python 函数。假设该函数是:calc(x,y,z)。如果我在 python 中使用一些变量运行这个函数,
>>> calc(1,2,3)
Run Code Online (Sandbox Code Playgroud)
它生成一个使用变量模拟某些内容的 C 代码(x=1, y=2, z=3),编译 C 代码并执行编译后的输出文件。
我想在 jupyter 笔记本中同时运行多个calc(x,y,z)具有不同 s 的 s 。(x,y,z)您可能已经注意到,问题在于 jupyter Notebook 中的单元格是按顺序执行的。如果我运行三个calc函数,则需要比运行一个函数的时间长三倍的时间。
我尝试了两种方法,但效果不佳。
multiprocessing模块:通过使用模块,可以calc在“一个单元”中同时执行多个操作。但为了以后的分析,我想同时执行多个单元,其中每个单元仅calc使用不同的处理器(或 CPU 内核)。使用ipyparallel细胞魔法(受此答案启发):导入后我尝试如下ipyparallel
# Cell 1
%%px --targets 0 # use processor 0
calc(1,1,1)
Run Code Online (Sandbox Code Playgroud)
。
# Cell 2
%%px --targets 1 # use processor 1
calc(2,2,2)
Run Code Online (Sandbox Code Playgroud)
。
# Cell 3
%%px …Run Code Online (Sandbox Code Playgroud)我的问题类似于这里的问题。我的Jupyter笔记本电脑中有一个牢房,可以运行很长时间。我想运行下一个单元格(变量不依赖于上一个单元格)以及上一个单元格。我不是要在CPU上进行多处理或共享作业。我要同时运行多个单元格的内容。默认情况下,它们按顺序运行。
就像运行两个不同的笔记本一样,但是为了连续性和共享对象,我想在同一笔记本的多个单元中运行变量。