0

I am writing a Python package which is designed to be imported into and called from within a jupyter notebook and convert the calling notebook into a specific format. The problem is I can't figure out how to get the path of the calling notebook from within the python script. I know I could just pass the path of the notebook to my python file, but it would be great if that would not be needed and you could just call the myPackage.convertMe() function without any arguments and the calling notebook gets converted.

something like that:

mypackage.py:

def convertMe():
    #some magic to convert the calling notebook

my_notebook.ipynb:

import myPackage
myPackage.convertMe()

I already tried inspect.stack()[1].filename but that only outputs the py3compact of the jupyter kernel.

Does anybody have an idea how to do that?

Acedon
  • 1
  • 1
  • Maybe use `sys.argv[0]`? But not completely sure if that will work for Jupiter notebooks – Lecdi May 09 '22 at 16:06
  • Sadly not, that just gives me the name of the called python script and not the name/path of the caller notebook – Acedon May 09 '22 at 16:16
  • I think to do what you want, you'd have to make an extension because you won't be able to get the path from the call in the notebook alone reliably, see [here](https://stackoverflow.com/q/12544056/8508004) and [here](https://discourse.jupyter.org/t/get-current-notebook-path-in-jupyterlab/9656/2?u=fomightez). For your own case & situation, if one of the hacks to get the path works, you may be able to make a workaround by pasing the path in when calling the script. How robust this will be in the future is questionable as things are moving more towards the underlying machinery of JupyterLab. – Wayne May 09 '22 at 16:26

0 Answers0