gpt4 book ai didi

python - 在 Python 解释器中随机更改提示

转载 作者:IT老高 更新时间:2023-10-28 21:43:17 25 4
gpt4 key购买 nike

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

我想像这样的互动:

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

最佳答案

根据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 中有一个消息列表,您可以附加或更改这些消息,这将影响控制台消息。

关于python - 在 Python 解释器中随机更改提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33668998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com