Jupyter notebook中五个有趣的魔法命令

开发
Jupyter notebook中有很多实用且鲜为人知的功能,可以实现有趣的操作,这次举五个简单的例子。

众​所周知,Jupyter notebook是一个交互式的Python shell,也就是IPython的封装版,非常适合用来进行数据分析和机器学习。

Jupyter notebook中有很多实用且鲜为人知的功能,可以实现有趣的操作,这次举五个简单的例子。

1. 脚本代码写入本地文件

%%file方法可以将脚本代码写入本地Py文件。

%%file E:\hello.py
def func_inside_script(x, y):
return x + y
print('Hello World')

图片

2. 执行Py文件

在notebook中可以直接执行Py文件,通过%run方法来实现。

%run hello.py

图片图片

3. 监测代码运行时间

可能你的代码需要精确的时间控制,那么%timeit方法可以帮到你。

%timeit [x**2 for x in range(100)] 

图片图片

4. 使用系统命令行

在windows中,使用命令行需要打开cmd窗口,如果你使用notebook,则可以通过!方法轻松执行命令行代码。

# 新建文件夹
my_dir = 'new_dir'
!mkdir $my_dir

5. 快速debug

bug是让人头疼的事,在notebook中可以轻松进行debug,使用%debug命令即可。

def some_func():
var = 'hello world'
for i in range(5):
print(i)
i / 0
return 'finished'

%debug
some_func()

图片

Jupyter notebook中还有很多有趣的魔法命令,感兴趣可以多摸索下。

责任编辑:赵宁宁 来源: Python大数据分析
相关推荐

2023-07-28 09:59:31

2023-11-05 12:31:07

Jupyter命令

2009-08-25 14:25:19

Eclipse 3.5

2024-01-03 16:37:26

Jupyter工具开源

2023-05-24 16:48:47

Jupyter工具技巧

2020-08-04 06:51:28

Jupyterpython开发

2022-10-10 23:19:02

Python脚本语言工具库

2020-09-24 05:50:46

PythonJupyter Not编程语言

2022-11-14 11:52:34

DataspellJupyterLabNotebook

2021-08-12 16:02:22

Jupyter NotPython命令

2019-09-22 18:53:27

Jupyter Not代码开发

2019-11-08 09:46:34

技术功能开发

2020-07-13 11:20:23

Python魔法命令代码

2022-05-05 12:25:46

Jupyter开发

2023-08-13 08:29:27

ChatGPT指令AI

2020-04-25 19:00:15

Linux终端命令

2023-12-10 14:19:31

JupyterPython编码

2021-03-19 09:48:10

Jupyter Not插件Python

2020-07-26 11:55:11

Jupyter Not扩展工具开发

2014-10-31 10:50:28

Linux命令行工具
点赞
收藏

51CTO技术栈公众号