Anyways to get the Jupyter notebook filename from PyCharm

I tried several ways recommended by Gemini but none of them work:

notebook_path = os.environ.get('JPY_SESSION_NAME')

Does not return the filename.

ipynbname package only works for the Jupyter notebooks running in the browser.

When I look into this workaround for VS code I discovery that PyCharm only has the directory path of the file, not the filename: ip.user_ns["_dh"][0]

I was trying to modify the file. So that Python can find the file under the directory with latest modified timestamp, but the PyCharm auto save does not triggered until the python code in a cell finishs execution.

There were also other ways recommended by Gemini to hack the Jupyter's API, but failed. So are there any other ways to get the Jupyter notebook filename from PyCharm?

 

Thanks a lot!

0

Hi Yz48 ,

 

You can get it from globals() with the following code:

import os
file_name = os.path.basename(globals()['__session__'])
0

But I got this error when I was trying your code in Jupyter notebook in PyCharm:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[1], line 2
      1 import os
----> 2 file_name = os.path.basename(globals()['__session__'])

KeyError: '__session__'
0

Do you have IPython installed in your interpreter? 

What are the outputs of print(globals()) in your notebook and pip list from the terminal with your env activated? 

0

This is the result of print(globals()):

{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', 'print(globals())'], '_oh': {}, '_dh': [PosixPath('/home/yaohuazhuo/PycharmProjects/PythonProject/dill_experiment')], 'In': ['', 'print(globals())'], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7ee7482746e0>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x7ee748276cf0>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x7ee748276cf0>, 'open': <function open at 0x7ee74ac062a0>, '_': '', '__': '', '___': '', 'plt': <module 'matplotlib.pyplot' from '/home/yaohuazhuo/bazel_output_base/py_venv/execroot/_main/bazel-out/k8-opt/bin/github/yhzhuo/python/jupyter_helper/.jupyter_helper_venv/lib/python3.13/site-packages/matplotlib/pyplot.py'>, '_pydevd_bundle': <module '_pydevd_bundle' from '/snap/pycharm-professional/628/plugins/python-ce/helpers/pydev/_pydevd_bundle/__init__.py'>, '_i': '', '_ii': '', '_iii': '', '_i1': 'print(globals())'}

And this is the output I get when I run !python -m pip list from my Jupyter's notebook's environment in PyCharm:

Package                   Version
------------------------- ------------
anyio                     3.7.1
argon2-cffi               25.1.0
argon2-cffi-bindings      25.1.0
asttokens                 3.0.1
atpublic                  7.0.0
attrs                     26.1.0
beautifulsoup4            4.14.3
bleach                    6.4.0
cachebox                  5.2.3
certifi                   2026.5.20
cffi                      2.0.0
chardet                   4.0.0
comm                      0.2.3
contourpy                 1.3.3
cycler                    0.12.1
debugpy                   1.8.21
decorator                 5.3.1
deepdiff                  9.1.0
defusedxml                0.7.1
dill                      0.4.1
entrypoints               0.4
executing                 2.2.1
fastjsonschema            2.21.2
file-read-backwards       3.2.0
fonttools                 4.63.0
ibis-framework            12.0.0
idna                      2.10
iniconfig                 2.3.0
ipykernel                 6.29.5
ipython                   9.14.1
ipython-genutils          0.2.0
ipython_pygments_lexers   1.1.1
jedi                      0.20.0
Jinja2                    3.1.6
jsondiff                  2.2.1
jsonschema                4.26.0
jsonschema-specifications 2025.9.1
jupyter-client            7.3.4
jupyter_core              5.9.1
jupyter-server            1.24.0
jupyterlab_pygments       0.3.0
kiwisolver                1.5.0
markdown-it-py            4.2.0
MarkupSafe                3.0.3
matplotlib                3.10.9
matplotlib-inline         0.2.2
mdurl                     0.1.2
mistune                   3.2.1
mysqlclient               2.2.8
nbclassic                 1.3.3
nbclient                  0.11.0
nbconvert                 7.17.1
nbformat                  5.10.4
nest-asyncio              1.6.0
notebook                  6.5.7
notebook_shim             0.2.4
numpy                     2.4.6
orderly-set               5.5.0
packaging                 26.2
pandas                    3.0.3
pandas-stubs              3.0.3.260530
pandocfilters             1.5.1
parso                     0.8.7
parsy                     2.2
pexpect                   4.9.0
pillow                    12.2.0
pip                       26.1.2
platformdirs              4.10.0
pluggy                    1.6.0
prometheus_client         0.25.0
prompt_toolkit            3.0.52
psutil                    7.2.2
ptyprocess                0.7.0
pure_eval                 0.2.3
pyarrow                   24.0.0
pyarrow-hotfix            0.7
pycparser                 3.0
Pygments                  2.20.0
PyMySQL                   1.2.0
pyparsing                 3.3.2
pytest                    9.0.3
python-dateutil           2.9.0.post0
PyYAML                    6.0.3
pyzmq                     27.1.0
referencing               0.37.0
requests                  2.25.1
rich                      15.0.0
rpds-py                   2026.5.1
Send2Trash                2.1.0
setuptools                82.0.1
six                       1.17.0
sniffio                   1.3.1
soupsieve                 2.8.4
sqlglot                   30.9.0
stack-data                0.6.3
terminado                 0.18.1
tinycss2                  1.5.1
toolz                     1.1.0
tornado                   6.1
traitlets                 5.15.1
typing_extensions         4.15.0
tzdata                    2026.2
urllib3                   1.26.20
wcwidth                   0.8.0
webencodings              0.5.1
websocket-client          1.9.0

 

0
Thank you for the update. 

I see a bunch of outdated packages (jupyter-server, notebook) and the absence of Jupyterlab. Please try the following: 
1. Create a new project with a new python interpreter
2. Create a new jupyter notebook 
3. Make sure Execution mode set to "JupyterLab" in Settings | Jupyter | Jupyter Servers
4. Run the code once again and let PyCharm install all the necessary packages. 

This should properly compose interpreter to have __session__ variable available in globals(). If this works as expected you can either move original project files here or reuse Python interpreter in the original project.
0

请先登录再写评论。