![](/img/trans.png)
[英]Shortcut to creating a jupyter cell in a non-notebook python file in vscode
[英]VScode: Automating conversion of python file to Jupyter notebook with a task
在VScode中,我可以用markdown和python單元格編寫一個python文件,然后通過命令面板將其轉換為筆記本。 一切都運作良好,但我想通過一項任務實現自動化。
我知道我可以為轉換定義一個快捷方式但是我仍然需要使用文件瀏覽器手動保存筆記本。 我可以通過任務自動執行此操作嗎? 如果是這樣,我如何訪問轉換功能? 這是VScode的一些內部功能還是可以通過命令行訪問此功能?
我在命令行中使用jupyter
命令嘗試了一些事情,但沒有任何運氣。 似乎沒有命令將python文件轉換為Jupyter筆記本。 另外,我找不到jupyter
命令的綜合文檔。
關於VScode中Jupyter筆記本的另一個問題:有沒有辦法隱藏單元格出現? 我知道如果我編輯筆記本的元數據是可能的,但我希望有更好的方法。
如果其他人仍然想知道這一點,我現在使用jupytext
將python文件轉換為jupyter筆記本。
我寫了兩個非常簡單的bash腳本來自動轉換和查看筆記本。
轉換:
#!/usr/bin/env bash
# retrieve file names and folder from arguments
full_fname=$1
fbase_name_no_ext=$2
dir_name=$3
workspace_folder=$4
full_path_no_ext="$dir_name/$fbase_name_no_ext"
notebook_save_path=$(cd ${dir_name}/.. && pwd)
# activate venv (venv should be in vscode workspace root)
source "${workspace_folder}/my_env/bin/activate"
echo "saving to: $notebook_save_path"
# convert to jupyter notebook
jupytext --to notebook ${full_fname}
# run all cells and save output to notebook file
jupyter nbconvert --to notebook --execute "${full_path_no_ext}.ipynb" --output "${notebook_save_path}/${fbase_name_no_ext}"
# cleanup intermediate notebook (contains only cells no output)
rm "${full_path_no_ext}.ipynb
查看筆記本:
#!/usr/bin/env bash
# retrieve file names and folder from arguments
fbase_name_no_ext=$1
dir_name=$2
workspace_folder=$3
source "${workspace_folder}/my_env/bin/activate"
# notebooks are stored in the parent directory of the source file
notebook_folder=$(cd ${dir_name}/.. && pwd)
# view notebook in a browser window
jupyter notebook "${notebook_folder}/${fbase_name_no_ext}.ipynb"
這是我的vscode任務文件:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "convert to NB",
"type": "shell",
"command": "${workspaceFolder}/convert",
"args": [
"${file}",
"${fileBasenameNoExtension}",
"${fileDirname}",
"${workspaceFolder}"
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "shared",
"showReuseMessage": true,
"clear": true
}
},
{
"label": "view NB",
"type": "shell",
"command": "${workspaceFolder}/viewNB",
"args": [
"${fileBasenameNoExtension}",
"${fileDirname}",
"${workspaceFolder}"
]
}
]
由於我不是bash專家,可能有更多的事情可以以更好的方式完成。 批評總是受歡迎的!
希望這對某人有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.