Python 2 pdb:在pdb提示符下运行时,语句的行为有所不同

时间:2018-04-29 21:41:50

标签: python python-2.7 pdb

这个问题可能会变得非常愚蠢,但在这里。以下语句触发特定电子邮件的异常:

  File "/Users/me/tools/maildir-deduplicate/maildir_deduplicate/mail.py", line 104, in body_lines
_, _, body = self.message.as_string().partition("\n\n")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 621: ordinal not in range(128)

如果我在PDB下运行并在提示符下手动测试它,则不会抛出异常并正确设置body

> /Users/me/tools/maildir-deduplicate/maildir_deduplicate/mail.py(105)body_lines()
-> _, _, body = self.message.as_string().partition("\n\n")
(Pdb) _, _, body = self.message.as_string().partition("\n\n")

但如果我点击下一行,它仍然会抛出异常:

(Pdb) n
UnicodeDecodeError: UnicodeD...ge(128)')
> /Users/me/tools/maildir-deduplicate/maildir_deduplicate/mail.py(105)body_lines()
-> _, _, body = self.message.as_string().partition("\n\n")

如果我中断了该语句,则会在partition()调用中抛出异常。

  File "/Users/me/tools/maildir-deduplicate/maildir_deduplicate/mail.py", line 106, in body_lines
body = self.message.as_string()
_, _, body = body.partition("\n\n")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 621: ordinal not in range(128)

pdb下运行相同的故事:如果我点击n,将会抛出异常,但如果我在提示时输入_, _, body = body.partition("\n\n")则不会抛出异常。

任何可能导致此问题的想法?

1 个答案:

答案 0 :(得分:3)

我怀疑你的代码中有from __future__ import unicode_literals

测试代码:

#!python2
from __future__ import unicode_literals
body = b'abc\n\ndef\xd7ghi'
_,_,body = body.partition('\n\n')

直接运行时(无pdb):

Traceback (most recent call last):
  File "C:\test.py", line 4, in <module>
    _,_,body = body.partition('\n\n')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 8: ordinal not in range(128)

pdb中逐步执行时,会收到UnicodeDecode错误:

> c:\test.py(2)<module>()
-> from __future__ import unicode_literals
(Pdb) n
> c:\test.py(3)<module>()
-> body = b'abc\n\ndef\xd7ghi'
(Pdb) n
> c:\test.py(4)<module>()
-> _,_,body = body.partition('\n\n')
(Pdb) n
UnicodeDecodeError: UnicodeD...ge(128)')      <<<<<<<<<<<<<<<<
> c:\test.py(4)<module>()
-> _,_,body = body.partition('\n\n')

当手动执行该行时,因为pdb不在__future__导入下,所以'\n\n'是一个字节字符串:

> c:\test.py(2)<module>()
-> from __future__ import unicode_literals
(Pdb) n
> c:\test.py(3)<module>()
-> body = b'abc\n\ndef\xd7ghi'
(Pdb) n
> c:\test.py(4)<module>()
-> _,_,body = body.partition('\n\n')
(Pdb) _,_,body = body.partition('\n\n')   <<<<<<<<<<<<< manual
(Pdb) body                                <<<<<<<<<<<<< worked!
'def\xd7ghi'
(Pdb) n
UnicodeDecodeError: UnicodeD...ge(128)')  <<<<<<<<<<<<< failed!
> c:\test.py(4)<module>()
-> _,_,body = body.partition('\n\n')