欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

10个jupyter notebook使用技巧

Python基础 迷途小书童 3年前 (2021-07-06) 2218次浏览 0个评论

环境

  • windows 10 64位
  • jupyter notebook

执行shell命令

jupyter notebookhappy 地敲着代码的时候,你会退出去执行 shell 命令吗?

其实大可不必,在 notebook 中就可以直接运行 shell 命令,只需要在命令最前面加上 !

jupyter notebook tricks

查看快捷键

我们都知道快捷键的重要性,熟练掌握快捷方式可以大大提升我们的工作效率,在 jupyter notebook 中,可以很方便的查看快捷方式

  • 按下Esc键,进入命令模式(command mode)
  • 按下h

jupyter notebook tricks

魔法命令

jupyter notebook,有很多的魔法命令( magic command ),它们非常有用,能让你的工作变得简单高效

jupyter notebook tricks

使用 %lsmagic 可以看到所有的魔法命令

jupyter notebook tricks

针对一些不熟悉的魔法命令,可以选中它,按下 shift+tab 来查看帮助信息,非常 nice

jupyter notebook tricks

统计单元格运行的时间

通过 %%time 可以获取到代码执行所消耗的时间,这个在我们做统计分析,性能调优上面非常有用

jupyter notebook tricks

多行同时编辑(多光标支持)

多行代码可以同时进行编辑,绝对的省时省力。按下 alt 键,利用鼠标左键进行选择

10个jupyter notebook使用技巧

当然,不推荐给变量这样命名,会被 leader 锤爆

隐藏部分输出信息

在语句的最后添加 ;,可以去掉部分恼人的输出信息。比如,当我们使用 matplotlib 画图的时候

jupyter notebook tricks

像中间红框标出的信息,大部分情况下,我们是不需要的,这时候,在 plt 代码的结尾加个逗号(英文的),就可以把它隐藏掉

plt.scatter(x, y);

jupyter notebook tricks

查看模块帮助信息

使用 ? 加方法名就可以很方便的查看帮助文档

jupyter notebook tricks

设置环境变量

机器学习/深度学习里,我们经常碰到使用环境变量的情况,在 jupyter notebook 也是可以设置修改环境变量的,借助于 %env

%env THIS_IS_ENV_EXAMPLE "xugaoxiang.com"

这里,THIS_IS_ENV_EXAMPLE 是环境变量,它的值是字串 xugaoxiang.com

jupyter notebook tricks

保存单元格内容到文件和在单元格中显示文件内容

使用 %%writefile 可以将单元格中的内容保存到外部的文件中

jupyter notebook tricks

使用 %pycat,以弹出框的形式显示外部文件的内容

jupyter notebook tricks

代码调试

使用 %pdb,可以在 notebook 中进行调试

jupyter notebook tricks

Automatic pdb calling has been turned ON
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-10-869a75f9e69b> in <module>
      4     raise NotImplementedError()
      5 
----> 6 pick_and_take()

<ipython-input-10-869a75f9e69b> in pick_and_take()
      2 def pick_and_take():
      3     picked = np.random.randint(0, 1000)
----> 4     raise NotImplementedError()
      5 
      6 pick_and_take()

NotImplementedError: 

> <ipython-input-10-869a75f9e69b>(4)pick_and_take()
      2 def pick_and_take():
      3     picked = np.random.randint(0, 1000)
----> 4     raise NotImplementedError()
      5 
      6 pick_and_take()

ipdb> 

可以看到,在 ipdb> 提示符后可以输入相应的指令,具体的可以参考链接 https://docs.python.org/3.8/library/pdb.html#debugger-commands

参考资料

喜欢 (0)

您必须 登录 才能发表评论!