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!
请先登录再写评论。
Hi Yz48 ,
You can get it from globals() with the following code:
But I got this error when I was trying your code in Jupyter notebook in PyCharm:
Do you have IPython installed in your interpreter?
What are the outputs of
print(globals())in your notebook andpip listfrom the terminal with your env activated?This is the result of
print(globals()):And this is the output I get when I run
!python -m pip listfrom my Jupyter's notebook's environment in PyCharm: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.