将交互式python中的默认repr从builtins.repr更改为reprlib.repr

时间:2013-02-27 13:57:49

标签: python console interactive repr

在交互式Python提示符下,当我没有将表达式foo的输出绑定到名称时,Python会将builtins.repr(foo)的输出写入终端。

在较新版本的Python中,存在an alternative repr implementation,它不会使具有长字符串表示的对象泛滥屏幕,如下所示:

In [297]: import random, string, reprlib

In [298]: long_str = ''.join(random.choice(string.ascii_letters) for _ in range(1000))

In [299]: print(repr(long_str))
'LcOKLSfEifohPxWIPZEbwLSTlXTLIeJNxBfTpfyjtpnetKHPoEqwgtcsSRGupdzTidaGoekQOrlRedOchiIFzVLlXxlRNJVCIlYaQhFUlzOpoHyfFLgYUaBhHtasSttYlUwlGcLwriLOWUxqdEfoVfFNbOANQgGPvByewTMCqFNRONFwumScFITLWUnlrxmzQkWNfhtEGWNNlKAdkfvmuxigyEtaZYmbQIxoQEUFfPAvGomrdDVMzprNNRfUqJMACWFEgpGNFBasgDRCYooSOvfXGtauuVHHKgbebLUVXtGZDJMTiSTMXxkPWjpiUqGCrxzEwkMmniIXuLDNjbNhqmaIePxDibJMbpDSiFutsQEHUhXfBbfymjMlyurWSlOFYGePRFFlWtNIrvwJaBuUCYQjGQFVnmUSrQHbbpDEkeOuBfTIsDZdQsyOsmJhmluwzhDDZPayCbOnkJgBkcshMISCVATIiPDwPShoBQuhkPSBMOiMJoRPILhoTYMroUUafuRbhgZgkyGGqKBTWJRDQqQZOiSAjRxgAyNHHhQLozVlCTTrNbjKDbKgvgbcmZOjdDaxqnYrajVxgBqJfMoAJegmqOVlVgZGnOZJOrmwAOaqYdqGavsskyLxsxFcUekORQjKxaFuvqemoqYujbnfabrZNiBLSXkxRThYFlRKyrpbUtmYbITSMADSEQMIGkoDGxsedwqzisDSJvTmzEiAAVZQGjnmLRpvKcPrmkYFyjJVpBHUhWaiqIFLrExLeSCZJurMteYdLWJgMCLbdlUqaChYqbBCoddXlwCMkHjQtbwOFOVroMaFuCCmeVUbjuvXeYOovXXewUXaWAmWvRlpoTRVqSLOUfZFYTHNPWUkoBADgYJdZboTxSZxlncxJlwtVpHqpjdRqfzgiAtKXrVVYQQBWcQhZzMFmNWRoDgdRSouqRUGqhPbKmLMszRrLmIDLmFJQuyPAJnENFmLbmXiendQKLfCKmpTICujAJsA'

In [300]: print(reprlib.repr(long_str))
'LcOKLSfEifoh...CKmpTICujAJsA'

In [301]: long_str
Out[301]: 'LcOKLSfEifohPxWIPZEbwLSTlXTLIeJNxBfTpfyjtpnetKHPoEqwgtcsSRGupdzTidaGoekQOrlRedOchiIFzVLlXxlRNJVCIlYaQhFUlzOpoHyfFLgYUaBhHtasSttYlUwlGcLwriLOWUxqdEfoVfFNbOANQgGPvByewTMCqFNRONFwumScFITLWUnlrxmzQkWNfhtEGWNNlKAdkfvmuxigyEtaZYmbQIxoQEUFfPAvGomrdDVMzprNNRfUqJMACWFEgpGNFBasgDRCYooSOvfXGtauuVHHKgbebLUVXtGZDJMTiSTMXxkPWjpiUqGCrxzEwkMmniIXuLDNjbNhqmaIePxDibJMbpDSiFutsQEHUhXfBbfymjMlyurWSlOFYGePRFFlWtNIrvwJaBuUCYQjGQFVnmUSrQHbbpDEkeOuBfTIsDZdQsyOsmJhmluwzhDDZPayCbOnkJgBkcshMISCVATIiPDwPShoBQuhkPSBMOiMJoRPILhoTYMroUUafuRbhgZgkyGGqKBTWJRDQqQZOiSAjRxgAyNHHhQLozVlCTTrNbjKDbKgvgbcmZOjdDaxqnYrajVxgBqJfMoAJegmqOVlVgZGnOZJOrmwAOaqYdqGavsskyLxsxFcUekORQjKxaFuvqemoqYujbnfabrZNiBLSXkxRThYFlRKyrpbUtmYbITSMADSEQMIGkoDGxsedwqzisDSJvTmzEiAAVZQGjnmLRpvKcPrmkYFyjJVpBHUhWaiqIFLrExLeSCZJurMteYdLWJgMCLbdlUqaChYqbBCoddXlwCMkHjQtbwOFOVroMaFuCCmeVUbjuvXeYOovXXewUXaWAmWvRlpoTRVqSLOUfZFYTHNPWUkoBADgYJdZboTxSZxlncxJlwtVpHqpjdRqfzgiAtKXrVVYQQBWcQhZzMFmNWRoDgdRSouqRUGqhPbKmLMszRrLmIDLmFJQuyPAJnENFmLbmXiendQKLfCKmpTICujAJsA'

我可以以某种方式告诉Python使用reprlib.repr而不是builtin.repr来表示交互式提示中的未分配输出吗?我最感兴趣的是那些适用于任何Python shell的答案,或者至少适用于IPython的答案。

1 个答案:

答案 0 :(得分:1)

您正在寻找的内容可能是sys.display_hookhttp://docs.python.org/2/library/sys.html#sys.displayhook