[英]How to get the path of the Databricks Notebook dynamically?
Please don't give solution for IPython/Jupyter notebooks.请不要为 IPython/Jupyter 笔记本提供解决方案。 The technology is different.
技术不一样。
I want to get the path of my Databricks notebook dynamically.我想动态获取我的 Databricks 笔记本的路径。 Which is something I can get from the UI "Copy File Path" as shown below.
这是我可以从 UI“复制文件路径”中获得的内容,如下所示。 I am not able to use
__file__
as that is giving me error.我无法使用
__file__
因为这给了我错误。
NameError: name '__file__' is not defined
If there is anything like that available for you, it can be found by inspecting globals()
and locals()
, eg如果有类似的东西可供您使用,可以通过检查
globals()
和locals()
,例如
print(globals())
In my case, the closest to this I found was:就我而言,我发现的最接近的是:
_dh
eg:例如:
print(_dh)
# ['/media/win10/Users/norok2/Downloads']
Each notebook has so-called "context" that contains a lot of information about environment, including the HTTP Path, hostname, etc. It could be retrieved as Python dict with something like this (it's simpler to convert to JSON & back than to fetch fields by .get
functions):每个笔记本都有所谓的“上下文”,其中包含许多关于环境的信息,包括 HTTP 路径、主机名等。它可以作为 Python dict 使用这样的东西进行检索(转换为 JSON 并返回比获取更简单)
.get
函数的字段):
import json
ctx = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
inside the ctx
dictionary there is a subdictionary named extraContext
, that contains field notebook_path
that is what you need:在
ctx
字典中有一个名为extraContext
,其中包含您需要的字段notebook_path
:
nb_path = ctx['extraContext']['notebook_path']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.