随机更改 Python 解释器中的提示

Randomly change the prompt in the Python interpreter

总在Python里看到>>>提示,有点无聊。随机更改提示前缀的最佳方法是什么?

我想象这样的互动:

This is a tobbaconist!>> import sys
Sorry?>> import math
Sorry?>> print sys.ps1
Sorry?
What?>>

问得好。 >>>提示在sys.ps1...sys.ps2。下一个问题是如何随机更改它。就当做手改的演示:

>>> import sys
>>> sys.ps1 = '<<<'
<<<sys.ps1 = '<<< '
<<< sys.ps2 = '.?. '
<<< for i in line:
.?. 

为了改变提示,我们使用

>>>import sys
>>>sys.ps1 = '=>'
=>

现在随机做的方法是这样的:

import random
import sys

random_prompts = ['->', '-->', '=>', 'Hello->']
sys.ps1 = random.choice(random_prompts)

要在 python 解释器启动时执行此操作,您可以遵循以下指南:https://docs.python.org/2/tutorial/appendix.html#the-interactive-startup-file

试试这个:

>>> import sys
>>> import random
>>> class RandomPrompt(object):
...     prompts = 'hello >', 'hi >', 'hey >'
...     def __repr__ (self): return random.choice(self.prompts)
... 
>>> sys.ps1 = RandomPrompt()
hello >1
1
hi >2
2

根据docs,如果你将一个非字符串对象赋值给sys.ps1那么它每次都会计算它的str函数:

If a non-string object is assigned to either variable, its str() is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.

很明显,您应该使其动态化!使用 __str__ 方法创建一个对象,您可以在其中放置您想要的任何逻辑:

class Prompt:
    def __str__(self):
        # Logic to randomly determine string
        return string

您也可以随时进行更改或向其中插入内容 class。因此,例如,您可以在 Prompt 中添加一个消息列表,您可以附加或更改这些消息,这将影响控制台消息。