Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

Randomly change the prompt in the Python interpreter

It's kind of boring to always see the >>> prompt in Python. What would be the best way to go about randomly changing the prompt prefix?

I imagine an interaction like:

This is a tobbaconist!>> import sys
Sorry?>> import math
Sorry?>> print sys.ps1
Sorry?
What?>>
question from:https://stackoverflow.com/questions/33668998/randomly-change-the-prompt-in-the-python-interpreter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the docs, if you assign a non-string object to sys.ps1 then it will evaluate the str function of it each time:

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.

Well now it's obvious, you should make it dynamic! Make an object with a __str__ method where you can place any logic you want:

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

You can also make changes or insert things into this class as you go too. So for example, you could have a list of messages in Prompt that you append to, or change, and that will affect the console message.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...