【Python进阶(四)】——魔术命令

🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972

   个人介绍: 研一|统计学|干货分享
         擅长Python、Matlab、R等主流编程软件
         累计十余项国家级比赛奖项,参与研究经费10w、40w级横向

【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=X1

NameError: 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=X1
        global x2 = undefined
        global X1 = undefined

NameError: 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=X1

ipdb> 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=X1
        global x2 = undefined
        global X1 = undefined

NameError: name 'X1' is not defined

5 程序运行的逐行统计:%prun与%lprun

  运行程序:

def myfunc1(n):
    n=n+1
    for i in [1,2,3,4,5]:
        n=n+i
    return(n)
%prun myfunc1(100)   #%prun:程序运行情况逐行统计
%lprun myfunc1(100)  #%lprun:程序运行情况逐行统计,并非ipython自带命令

6 内存使用情况的统计: %memit

  运行程序:

%load_ext memory_profiler  #导入包
%memit myfunc2(100)
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小墨&晓末

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值