在交互式 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 的答案感兴趣。