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

Python 2 pdb: a statement behaves differently when run at the pdb prompt

这个问题可能真的很愚蠢,但就是这样。以下语句触发特定电子邮件的异常:

  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") 则不会抛出异常。

知道是什么原因造成的吗?

我怀疑你的代码中有一个 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')