在 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 专家,因此可能有很多事情可以以更好的方式完成。随时欢迎批评!
希望这对某人有帮助。
关于python - VScode : Automating conversion of python file to Jupyter notebook with a task,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722347/