随机更改Python interp中的提示

2024-10-03 02:44:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想象这样的互动:

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

Tags: 方法importissysmaththiswhatprint
3条回答

试试这个:

>>> 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

您也可以在进行更改或在该类中插入内容。例如,您可以在Prompt中添加或更改消息列表,这将影响控制台消息。在

对于更改提示,我们使用

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

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

^{pr2}$

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

相关问题 更多 >