Python jupyter notebook简易上手使用教程(vscode+python extension)

Python jupyter notebook简易上手使用教程(vscode+python extension)

大家都是使用过Python的命令行交互

比如Python安装包自带的IDLE的命令行模式
在这里插入图片描述

Jupyter Notebook 解决的问题和自我定位

可以看到,首先,界面不美观,其次,运行结果无法保存,所以大家实际开发是很少用这些,但是命令行模式用来测试片段代码还是很方便,省去创建文件,编码,配参数,按运行键等过程

但是其优点也是有的,如果我们能美化它的页面显示,增加注释文本,而且注释文本显示可以用很好的格式渲染,支持片段代码快捷运行,还能保存为文件长期保存,如果还可以和多人共享,那不就最好了!

对,Jupyter Notebook就做了这样的一件事:
来看官方的自我定位:

The notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results

看一眼jupter notebook的结果展示:
在这里插入图片描述
还有更好的图标展示,我就不在这推广他了,毕竟这是一个教程,以上只是为了让你刚好的理解jupyter notebook的产生目的,下面开始介绍环境搭建

VS code + Python + jupyter notebook 搭建

此处翻译,简化vscode的流程

1 安装python环境

2 安装vs code

3 vs code 安装Python extension

此处无需安装其他jupyter 拓展,有截图可看出,Python extension以及原生支持了Jupyter Notebook
在这里插入图片描述

4 创建Python文件(跳过此步不操作,从第五步操作)

编辑python文件时添加一些特定格式,Python extension 便可以使得jupyter运行
# %%:python 代码
# %% [markdown] : 支持markdown格式的注释说明

左边:是编辑的代码
右边:是vscode运行后界面展示
在这里插入图片描述

5 创建jupyter notebook文件

建议后续步骤参照Working with Jupyter Notebooks in Visual Studio Code
  1. 按 Ctrl+shift+P 输入Python: Create Blank New Jupyter Notebook,创建.ipynb文件
    在这里插入图片描述
    如果此时你的python环境没有安装 jupyter notebook 模块,vscode会自动给你安装,并且同时安装一个MicroSoft Python Language Server,在vscode最下面可以看到安装进度(可能会比较慢)

  2. 创建成功可以看到
    在这里插入图片描述

6 开始愉快的编辑

  1. 默认会有一个空的代码格,输入python代码便好
    在这里插入图片描述
    在这里插入图片描述

  2. 添加代码格(code cell)在这里插入图片描述

  3. 运行代码格
    在这里插入图片描述

  4. 运行多个代码格
    在这里插入图片描述

  5. 移动代码格
    在这里插入图片描述

  6. 删除代码格
    在这里插入图片描述

  7. 转换代码格为 支持markdown的文本格
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  8. 安装在vscode安装IntelliSense插件,支持代码补齐
    在这里插入图片描述

  9. 程序变量 和 数据查看器
    在这里插入图片描述

  10. 图形查看器
    在这里插入图片描述

  11. 将.ipynb文件转为.py 文件
    在这里插入图片描述
    你就会发现转换后得.py文件和步骤五自己编写的.py文件格式相同,本质就是使用#%%和#%%[markdown]操作符进行格式控制

7 jupyter notebook 实现逻辑

jupyter notebook由服务器端和浏览器网页显示组成

  • A web application:
    a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output.

  • Notebook documents:
    a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects.

  1. 启动 notebook server,你就可以在浏览器打开网址 http://127.0.0.1:8888 查看浏览器显示

jupyter notebook

  1. vscode 应用本身基于一个浏览器chromium内核实现的web桌面应用,所以vscode可以很好的支持jupyter notebook,观察vscode的cosole输出,其逻辑是:
    • 命令行启动notebook server
    • vscode连接到notebook server
    • 显示,加载内容

以上

发布了17 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/TowerOs/article/details/103986157