在交互式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的答案。
答案 0 :(得分:1)
您正在寻找的内容可能是sys.display_hook
:http://docs.python.org/2/library/sys.html#sys.displayhook。