简体   繁体   English

Jupyter / IPython笔记本可以在URL中获取参数吗?

[英]Can a Jupyter / IPython notebook take arguments in the URL?

Is it possible to write an Jupyter notebook such that parameters can be passed in via the URL of the notebook? 是否可以编写一个Jupyter笔记本,以便参数可以通过笔记本的URL传入?

Example, for a URL such as this: 例如,对于这样的URL:

http://jupyter.example.com/user/me/notebooks/notebook1.ipynb?Variable1=Value1&Variable2=Value2

how could access Variable1 and Variable2 inside the Jupyter cell? 如何访问Jupyter单元格内的Variable1Variable2

You need to find out the URL using JavaScript and pass it to the IPython kernel: 您需要使用JavaScript找到URL并将其传递给IPython内核:

from IPython.display import HTML
HTML('''
    <script type="text/javascript">
        IPython.notebook.kernel.execute("URL = '" + window.location + "'")
    </script>''')

or: 要么:

%%javascript
IPython.notebook.kernel.execute("URL = '" + window.location + "'");

Then in the next cell: 然后在下一个单元格中:

print(URL)

After this you can use the tools in the standard library (or plain string operations) to pull out the query parameters. 在此之后,您可以使用标准库中的工具(或纯字符串操作)来提取查询参数。

You just need to take the values with javascript and push them to the ipython kernel like in the John Schmitt's link. 您只需要使用javascript获取值并将其推送到ipython内核,就像在John Schmitt的链接中一样。

Cell [1]: 细胞[1]:

%%javascript
function getQueryStringValue (key)
{  
    return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
IPython.notebook.kernel.execute("Var1='".concat(getQueryStringValue("Variable1")).concat("'"));
IPython.notebook.kernel.execute("Var2='".concat(getQueryStringValue("Variable2")).concat("'")); 

And in another cell you can retrieve the python variables named Var1 and Var2: 在另一个单元格中,您可以检索名为Var1和Var2的python变量:

>>>print Var1
Value1

And: 和:

>>>print Var2
Value2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM