🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972
个人介绍: 研一|统计学|干货分享
擅长Python、Matlab、R等主流编程软件
累计十余项国家级比赛奖项,参与研究经费10w、40w级横向
文章目录
- 1 运行.py文件: %run
- 2 统计运行时间: %timeit与%%timeit
- 2.1 %timeit
- 2.2 %%timeit
- 3 更改异常信息的显示模式:%xmode
- 3.1 mode:Plain
- 3.2 mode: Verbose
- 4 调试程序: %debug
- 5 程序运行的逐行统计:%prun与%lprun
- 6 内存使用情况的统计: %memit
【Python进阶(四)】——魔术命令,建议收藏!
该篇文章首先利用Python展示了其常的魔术命令,包括类的运行程序;运行时间计算;更在异常信息;调试程序;程序运行情况;内存使用情况的相关魔术命令。
1 运行.py文件: %run
运行程序:
import os
os.getcwd() #查询当前工作目录
os.chdir("D:\\pythonjupyter") #改变当前工作目录
%run testme.py
testme.py 为"D:\pythonjupyter"工作路径下的.py文件
2 统计运行时间: %timeit与%%timeit
2.1 %timeit
运行程序:
%timeit myList2=[n**2 for n in range(100)]%timeit x=1#查看某行代码运行时间
运行结果:
26.3 µs ± 522 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
10.7 ns ± 0.414 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
2.2 %%timeit
运行程序:
%%timeit x=1 #查看多行代码所需时间(%%timeit前不能有任何代码,注释类的代码都不行,否者报错)
x=x+2
x=x*2
运行结果:
2.71 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit与%%timeit区别: %timeit为统计单行代码运行时间;%%timeit为统计多行代码所需时间。
3 更改异常信息的显示模式:%xmode
3.1 mode:Plain
运行程序:
%xmode Plain
x1=2
x2=X1
运行结果:
Exception reporting mode: Plain
Traceback (most recent call last):File "<ipython-input-115-59f69ef917e0>", line 3, in <module>x2=X1NameError: name 'X1' is not defined
3.2 mode: Verbose
运行程序:
%xmode Verbose
x1=2
x2=X1
运行结果:
Exception reporting mode: Verbose
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-116-a2ff507801f7> in <module>1 get_ipython().run_line_magic('xmode', 'Verbose')2 x1=2
----> 3 x2=X1global x2 = undefinedglobal X1 = undefinedNameError: name 'X1' is not defined
4 调试程序: %debug
运行程序:
%debug
x1=2
x2=X1
运行结果:
> <ipython-input-116-a2ff507801f7>(3)<module>()1 get_ipython().run_line_magic('xmode', 'Verbose')2 x1=2
----> 3 x2=X1ipdb> q
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-117-e8d5ec0ce5b1> in <module>1 get_ipython().run_line_magic('debug', '')2 x1=2
----> 3 x2=X1global x2 = undefinedglobal X1 = undefinedNameError: name 'X1' is not defined
5 程序运行的逐行统计:%prun与%lprun
运行程序:
def myfunc1(n):n=n+1for i in [1,2,3,4,5]:n=n+ireturn(n)
%prun myfunc1(100) #%prun:程序运行情况逐行统计
%lprun myfunc1(100) #%lprun:程序运行情况逐行统计,并非ipython自带命令
6 内存使用情况的统计: %memit
运行程序:
%load_ext memory_profiler #导入包
%memit myfunc2(100)