在交互式 Python 提示符上,当我没有将表达式 foo
的输出绑定(bind)到名称时,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 的答案。
我是一名优秀的程序员,十分优秀!