ipython / ipykernel

IPython Kernel for Jupyter
https://ipykernel.readthedocs.io/en/stable/
BSD 3-Clause "New" or "Revised" License
631 stars 361 forks source link

Add __file__ variable supported by traditional Python scripts to Notebook environment #227

Open palewire opened 7 years ago

palewire commented 7 years ago

It would be cool, if the __file__ variable present in traditional Python scripts also existed with a notebook. This could be especially helpful when generating dynamic paths.

Other Python double underscore methods, such as __doc__ and __name__, are already present. Why not add this one?

mgeier commented 6 years ago

FWIW, a traditional interactive Python session doesn't define __file__ either.

I guess the kernel isn't associated with any file. It's just started and waits for Jupyter clients to connect. It doesn't even necessarily have to know that one of the clients happens to be a Jupyter Notebook which happens to have physical file associated with it.

If you want to get the notebook name from within the running Notebook, you can try to get it via JavaScript. In the JavaScript namespace there seem to be several related things (and probably more?):

geyang commented 4 years ago

This request has been kicked around quite a bit in the past. This requires client-side information. Implementing this as a cell magic would pretty clean and sensible.

%__file__
print(__file__)
# >>> "uvpn_experiments/icml_2020/local_metric_analysis.ipynb"