![](/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.