1

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

在较新版本的 Python 中,存在一种替代repr实现,它不会在屏幕上显示具有长字符串表示的对象,如下所示:

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 的答案感兴趣。

4

1 回答 1

1

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

于 2013-02-27T15:41:05.907 回答