Jupyter / IPython notebook 可以在 URL 中接受参数吗?
Can a Jupyter / IPython notebook take arguments in the URL?
是否可以编写一个 Jupyter 笔记本,以便通过笔记本的 URL 传递参数?
例如,对于这样的 URL:
http://jupyter.example.com/user/me/notebooks/notebook1.ipynb?Variable1=Value1&Variable2=Value2
如何在 Jupyter 单元中访问 Variable1
和 Variable2
?
您需要使用 JavaScript 找出 URL 并将其传递给 IPython 内核:
from IPython.display import HTML
HTML('''
<script type="text/javascript">
IPython.notebook.kernel.execute("URL = '" + window.location + "'")
</script>''')
或:
%%javascript
IPython.notebook.kernel.execute("URL = '" + window.location + "'");
然后在下一个单元格中:
print(URL)
之后就可以使用标准库中的工具(或者纯字符串操作)来提取查询参数了。
您只需要使用 javascript 获取值并将它们推送到 ipython 内核,就像 John Schmitt 的 link.
单元格 [1]:
%%javascript
function getQueryStringValue (key)
{
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\?]" + escape(key).replace(/[\.\+\*]/g, "\$&") + "(?:\=([^&]*))?)?.*$", "i"), ""));
}
IPython.notebook.kernel.execute("Var1='".concat(getQueryStringValue("Variable1")).concat("'"));
IPython.notebook.kernel.execute("Var2='".concat(getQueryStringValue("Variable2")).concat("'"));
在另一个单元格中,您可以检索名为 Var1 和 Var2 的 python 个变量:
>>>print Var1
Value1
并且:
>>>print Var2
Value2
是否可以编写一个 Jupyter 笔记本,以便通过笔记本的 URL 传递参数?
例如,对于这样的 URL:
http://jupyter.example.com/user/me/notebooks/notebook1.ipynb?Variable1=Value1&Variable2=Value2
如何在 Jupyter 单元中访问 Variable1
和 Variable2
?
您需要使用 JavaScript 找出 URL 并将其传递给 IPython 内核:
from IPython.display import HTML
HTML('''
<script type="text/javascript">
IPython.notebook.kernel.execute("URL = '" + window.location + "'")
</script>''')
或:
%%javascript
IPython.notebook.kernel.execute("URL = '" + window.location + "'");
然后在下一个单元格中:
print(URL)
之后就可以使用标准库中的工具(或者纯字符串操作)来提取查询参数了。
您只需要使用 javascript 获取值并将它们推送到 ipython 内核,就像 John Schmitt 的 link.
单元格 [1]:
%%javascript
function getQueryStringValue (key)
{
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\?]" + escape(key).replace(/[\.\+\*]/g, "\$&") + "(?:\=([^&]*))?)?.*$", "i"), ""));
}
IPython.notebook.kernel.execute("Var1='".concat(getQueryStringValue("Variable1")).concat("'"));
IPython.notebook.kernel.execute("Var2='".concat(getQueryStringValue("Variable2")).concat("'"));
在另一个单元格中,您可以检索名为 Var1 和 Var2 的 python 个变量:
>>>print Var1
Value1
并且:
>>>print Var2
Value2