[英]Jupyter Notebook: Run a Notebook cell programmatically within a loop
我想在函數中run a specific jupyter code cell
。 我發現執行單元格的唯一選擇是:
IPython.display.Javascript("Jupyter.notebook.execute_cells([4])")
這是可行的,但是一旦我將代碼實現到python函數中,它就不再執行任何操作:
if version_val == ():
IPython.display.Javascript("Jupyter.notebook.execute_cells([4])")
這是我嘗試執行的全部代碼(每個單元格都標記在一個新塊中):
1:
import os
import ipywidgets as widgets
import IPython
from IPython.display import Javascript
import plotly as py
import plotly.graph_objs as go
2:
if os.path.exists("Test"):
test_exists = True
else:
test_exists = False
print("Found no folder named 'Test'!")
if test_exists:
subfolder = os.listdir("Test")
3:
enter2 = widgets.Button(description = "Enter")
version_val = ()
def update_d(self):
IPython.display.clear_output()
global dt
dt = dropdown_testcase.value
global subsubfolder
subsubfolder = os.listdir(r"Test\{}".format(dt))
global dropdown_version
dropdown_version = widgets.SelectMultiple(options=subsubfolder, description="Mark Both <br> for <br>Comparison")
display(dropdown_version)
enter2.on_click(start_all)
display(enter2)
def start_all(self):
global version_val
version_val = dropdown_version.value
if version_val == ():
print("Choose your data !")
if version_val == ('Files',):
IPython.display.Javascript("Jupyter.notebook.execute_cells([3])")
if test_exists:
dropdown_testcase = widgets.Dropdown(options=subfolder, description="Testcase")
enter = widgets.Button(description = "Enter")
enter.on_click(update_d)
display(dropdown_testcase)
display(enter)
4:
x = [0,1,2,3]
y = [0,1,2,3]
trace = [go.Scatter(x=x, y=y, mode="markers")]
fig = go.Figure(data=trace)
py.offline.iplot(fig)
我需要在最后一個單元格中執行繪圖。
它需要您在筆記本文件夾中創建一個“測試”文件夾,以及一個名為“任意”的子文件夾。 並且在該子文件夾中必須是一個名為“文件”的子子文件夾。
有人知道如何解決這個問題嗎?
提前致謝!
(我的答案涉及如何run a specific jupyter code cell
)
在Jupyter筆記本上,您可以使用In[]
和Out[]
訪問單元格的內容。 這是一個簡單的代碼嘗試:
假設代碼單元[13]已經完成一些計算:
In [13]: 1+2+3+4+5
Out [13]: 15
在同一筆記本中的某個位置,您可以像這樣訪問和運行該單元格中的代碼:
print("Result from execution the cells above:", eval(In[13]), Out[13])
您應該得到的結果為
('Result from execution the cell above:', 15, 15)
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.