Sujet : Re: How to Add ANSI Color to User Response
De : pf (at) *nospam* pfortin.com (Pierre Fortin)
Groupes : comp.lang.pythonDate : 11. Apr 2024, 01:44:49
Autres entêtes
Message-ID : <mailman.91.1712796736.3468.python-list@python.org>
References : 1 2
User-Agent : Claws Mail 4.2.0git67 (GTK 3.24.41; x86_64-pc-linux-gnu)
On Thu, 11 Apr 2024 04:50:49 +1000 WordWeaver Evangelist via Python-list
wrote:
Hello List,
>
I have a simple question. I use the following textPrompt in some of my Jython modules:
'\n[1;33mYour choice is? (A B C D E): ', maxChars=1, autoAccept=False, forceUppercase=True)
Is there a way to add an ANSI color code to the end where the conditions are, so that the color of the user’s input is of a color of my choosing, instead of just white?
Thank you very much in advance.
Kind regards,
Bill Kochman
Over the years, I've tried different mechanisms for applying colors until
I got my hands on f-stings; then I created a tiny module with all the
colors (cR, cG, etc) which made my life so much simpler (attached). The
module includes background colors (bX); but I very rarely use those.
Then, I just use the module like this:
# place the module in a directory where your script is
# e.g., $ mkdir mymods (rename as desired)
from mymods.colors import *
# or just include the contents inline
# this simply switches from one color to the next
print( f"{cR}red, {cB}blue, {cG}green {cO}are colors." )
# color just the response
ans = input( f"Answer?: {cG}" ) # turn off color on next line
print( f"{cO}You entered: {cY}{ans}{cO}" )
# ^^^^
# to turn off each color (white commas), change the above to:
print( f"{cR}red{cO}, {cB}blue{cO}, {cG}green {cO}are colors." )
On Windows, you'll need to add this *before* using the colors:
import os
if os.name == 'nt': # Only if we are running on Windows
from ctypes import windll
w = windll.kernel32
# enable ANSI VT100 colors on Windows.
w.SetConsoleMode(w.GetStdHandle(-11), 7)
HTH,
Pierre