###### tags: `python note` `python` # ipynb to py 自動化 ## 拿到當前ipynb檔案名稱 ### solution #### get current .ipynb file name 開發環境:VScode ```python a = globals() b = a['__vsc_ipynb_file__'] print(b.split('\\')[-1]) # ``` 每種檔案(.py、.ipynb等)都有隱藏的變數/屬性(像是__main__)。 globals()就像是把ipynb的所有隱藏變數列出來,是一個dict。 當前檔案名稱就在'__vsc_ipynb_file__'的value內,把它拿出來就好了 #### sol: ```python if __name__ == "__main__": def save_to_py(): dict_env_var = globals() key = dict_env_var['__vsc_ipynb_file__'] current_file_name = key.split('\\')[-1] !jupyter nbconvert --to script {current_file_name} save_to_py() ``` ### 會失敗的解法 [How do I get the current IPython / Jupyter Notebook name](https://stackoverflow.com/questions/12544056/how-do-i-get-the-current-ipython-jupyter-notebook-name) 1. ipynbname 沒屁用 : 跑nb_name = ipynbname.name()跑不會停,github issue也有這個問題,作者沒回 2. ipyparams 沒屁用 : 跑currentNotebook = ipyparams.notebook_name,不會回傳東西,github issue也有這個問題,作者沒回 3. 用javascript語法去跑,還沒試。 [link:Can a jupyter notebook find its own filename?](https://stackoverflow.com/questions/52691468/can-a-jupyter-notebook-find-its-own-filename) ## 用code把ipynb轉成py [安装jupyter nbextensions拓展问题和解决方案](https://www.cnblogs.com/djma/p/16310876.html)