5

Please don't give solution for IPython/Jupyter notebooks. The technology is different.

I want to get the path of my Databricks notebook dynamically. Which is something I can get from the UI "Copy File Path" as shown below. I am not able to use __file__ as that is giving me error.

NameError: name '__file__' is not defined

enter image description here

2
  • @Evgeny no it isn't. My question is for Databricks. Commented Jun 29, 2019 at 22:02
  • This question is about databricks, a completely different platform from the referenced "duplicate". Commented Nov 9, 2021 at 14:25

2 Answers 2

4

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):

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:

nb_path = ctx['extraContext']['notebook_path']
Sign up to request clarification or add additional context in comments.

Comments

1

If there is anything like that available for you, it can be found by inspecting globals() and locals(), e.g.

print(globals())

In my case, the closest to this I found was:

_dh

e.g.:

print(_dh)
# ['/media/win10/Users/norok2/Downloads']

6 Comments

For Databricks it is giving ['/databricks/driver'] , which is not my expected output.
Have you asked DataBricks customer care? It may be your best shot.
I am using community version of DBR. I don't think they will help.
Hi @AnirbanNag'tintinmj' you can retrieve the notebook paths using their REST API: docs.databricks.com/api/latest/workspace.html#list However, you have mentioned that you are using the community version. So please confirm first by trying API call if you have access to the REST API or not.
I want to get the notebook path where I am writing the code. So I can use that for logging purpose.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.