python pdb 安装_简说Python之ipython的pdb调试

Ubuntu 18.04.1 LTS

Python使用的是虚拟环境:virutalenv

Python的版本:Python 3.6.9

简说Python之ipython

1.安装ipython

pip install ipython

2.ipython的使用

In [1]: run utils.py

In [2]: cat utils.py

# coding=utf-8

import os

import hashlib

from functools import partial

from config import UPLOAD_FOLDER

HERE = os.path.abspath(os.path.dirname(__file__))

def get_file_md5(f, chunk_size=8192):

h = hashlib.md5()

while True:

chunk = f.read(chunk_size)

if not chunk:

break

h.update(chunk)

return h.hexdigest()

def humanize_bytes(bytesize, precision=2):

abbrevs = (

(1 << 50, 'PB'),

(1 << 40, 'TB'),

(1 << 30, 'GB'),

(1 << 20, 'MB'),

(1 << 10, 'kB'),

(1, 'bytes')

)

if bytesize == 1:

return '1 byte'

for factor, suffix in abbrevs:

if bytesize >= factor:

break

return '%.*f %s' % (precision, bytesize / factor, suffix)

get_file_path = partial(os.path.join, HERE, UPLOAD_FOLDER)

In [3]: humanize_bytes(100)

Out[3]: '100.00 bytes'

In [4]: humanize_bytes(430004)

Out[4]: '419.93 kB'

In [5]: humanize_bytes(430004342342)

Out[5]: '400.47 GB'

这样可以不启动所有的py程序,直接测试某一个函数的功能。通过输入参数,得到输出。

函数的性质,把它看成一个黑盒子。测试它的输入输出。

humanize_bytes通过测试可以知道,它就是格式化数字,统计为多少字节,KB,MB,GB等。

3.ipython的debug调试。

python写了一个简单的递归程序

(zsdpy1) $ vi recursive.py

# coding=utf-8

def recu(n):

print ("level 1 value :",n);

if(n>2):

recu(n-1)

print ("--level 2 value :",n);

recu(5)

进入调试

In [4]: run -d recursive.py

1 # coding=utf-8

----> 2 def recu(n):

3 print ("level 1 value :",n);

4 if(n>2):

5 recu(n-1)

b设置断点命令,进入调试模式输入b xx(xx为行数)。

n命令单步执行,不会进入函数内部

s命令单步执行,会进入函数内部

a是打印出当前函数的参数值

j 是跳转到某一行执行有点类似b和c指令结合,具体使用j xx(xx为行数)

q,退出pdb调试模式

这里我们输入s命令,单步调试,看看这个递归程序是如何运行的。

ipdb> s

## 直接跳入到了recu(5)的过程

> /home/zsd/web_develop/recursive.py(8)()

4 if(n>2):

5 recu(n-1)

6 print ("--level 2 value :",n);

7

----> 8 recu(5)

ipdb> s

## 运行recu(n)的函数

> /home/zsd/web_develop/recursive.py(2)recu()

1 # coding=utf-8

----> 2 def recu(n):

3 print ("level 1 value :",n);

4 if(n>2):

5 recu(n-1)

## 输出函数值5

> /home/zsd/web_develop/recursive.py(3)recu()

1 # coding=utf-8

2 def recu(n):

----> 3 print ("level 1 value :",n);

4 if(n>2):

5 recu(n-1)

ipdb> s

level 1 value : 5

> /home/zsd/web_develop/recursive.py(4)recu()

2 def recu(n):

3 print ("level 1 value :",n);

----> 4 if(n>2):

5 recu(n-1)

6 print ("--level 2 value :",n);

然后就会一直循环,到2的时候,在循环出来。有兴趣的可以s继续单步调试

其输出结果是:

level 1 value : 5

level 1 value : 4

level 1 value : 3

level 1 value : 2

--level 2 value : 2

--level 2 value : 3

--level 2 value : 4

--level 2 value : 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值