How can I determine if the terminal can display colours in python? - python

In most terminals, I can use ANSI-Colour-Codes in Python. e.g. print("\033[92mHello World") would print out Hello World in green. However in other terminals this does not work and it prints the [94mHello World literally.
How can I determine if the terminal that is used can display colours within code. (This is not an issue of determining if an individual terminal can display colours. What I want is to differentiate between terminals within code.)

I used this code:
import crayons
print(crayons.red('red'))
print(crayons.yellow('yellow'))
print(crayons.green('green'))
print(crayons.cyan('cyan'))
print(crayons.blue('blue'))
print(crayons.magenta('magenta'))
print(crayons.white('white'))
print(crayons.black('black'))
To get this:
So now I know what all of the colors look like for my compiler.

Related

How to change color of the terminal using Python

I am making my own terminal and I want to change all text colors to the user input. Please help me!
You are going to have to provide way more context for this question. What do you mean by making your own terminal? Are you building a terminal application or are you customizing a terminal?
If you mean you are running a python application and want to color the output of the script then consider using colorama
https://pypi.org/project/colorama/
You can use ANSI_escape_code like this: \033[CODE_HERE;ANOTHER_CODE_HEREmYOUR_CONTENT_HERE.
Example for bold + blinking text (\033[0m is to reset display to default values):
print("\033[1;5mdede\033[0m")
Another example:
print("\033[1;41mRed bold text\033[0;41mRed normal text\033[0mnormal text")
Will result to:
[]

Is there a way to dynamically change the font color in Jupyter markdown?

I am using Jupyter to create a report file of an analysis I'm doing. At the end of each analysis I'll provide a summary of how many errors/irregularities the analysis has found. I was wondering if there is a way to dynamically change the font color based on the results. e.g. let's say we have a variable called "font_color" and we have a if statement that sets the variable to "Red" if there are errors and "Black" if there is none, now in Jupyter markdown set the color as:
In code cell:
font_color = *IF statement to define color*
In markdown cell:
<font color={{font_color}}>
- Testing
I'm open to suggestions and if there is a better way to dynamically change font colors.
Yes, in Jupyter notebooks you can use code to output markdown as well the standout and stderr channels. And also in Jupyter notebooks you can use HTML within the markdown to color code parts of text. Combining those, you could customize something like this for your report generation:
from IPython.display import Markdown, display
a = "Good"
if a == "Good":
font_color="green"
else:
font_color="red"
def printmd(string):
display(Markdown(string))
printmd("Summary:")
printmd(f'**<font color={font_color}>Status for a.</font>**')
Also see here and here.

How to change easyGUI python text color

I want to change the text color of msgbox, ynbox and the output text in easyGUI.
Please help!
Quoting from this site:
EasyGUI won;t help change colour, it is just a way of making
a command line script act like a GUI - by popping up dialog
boxes to capture input and dsplay messages. It replaces
raw_input and print with dialogs.
--------code--------
from WConio import textcolor
apples_left = 5
print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the basket."
The output works, but there is one snag. I think that I am leaving
something out because it has the word "None" on both sides of the
variable.
This could be an easy solution for your problem.
You may get WConio from here:
http://newcenturycomputers.net/projects/wconio.html
If you face python not found error at the time of installation then you may try following this answer.
UPDATE:
There is one more package named Colorama, which is cross-platform for colored terminal text and pretty much stable. You may give it a try as well.

Python Terminal Menu? Terminal Coloring? Terminal progress display?

I have a project that uses Python (2.* flavors) extensively and I am wondering if there is a terminal menu library or something to that effect? I am looking to breathe some flavor and life into my script by simplifying some of the options using arrow key highlightable options, some color, etc etc. I vaguely recall there being a way to make a bash shell terminal menu but I'm not at all sure how I would pass user input from bash to the python script, perhaps have a bash terminal menu push the script call with sysarggs? I'd like something on the python side if possible. Any suggestions?
Also just a random question, kind of fits in here since we're on the topic of terminal aesthetics, what's the best way to handle a counter? My script looks for image files, then when it finds one it clears the terminal with a subprocess call to clear and then prints the total images found again IE 10 images, find one, clear, print "11 images found", sometimes my script works REAL fast and I feel this detriments performance. Thoughts?
Thanks so much everyone, I love stack overflow ;)
Edit - Thanks for all the quick responses! I have alot of options to mull over. I gave everyone an upvote because all of your responses are helpful. I will check out all the libraries when I get home and try to pick one of you for an answer depending on what hashes out the best, wish I could pick you all though because all of your answers are relevant! Much appreciated folks. I'll report back in once I get home from work and get a chance to get some coding in ;)
Edit 2 - A clarification on the counter/progress display, looking for a way to keep this from detrimenting performance when my script finds thousands of images in a very short ammount of time, this is real chopped up python...
for each item in list:
if item ends with .jpg
cnt=cnt+1
do stuff with image file
subprocess.call('clear')
print str(cnt)+" total images processed."
Thanks again!
Check out Clint (*C*ommand *L*ine *IN*terface *T*ools)!
Official page: https://github.com/kennethreitz/clint
Great overview: http://www.nicosphere.net/clint-command-line-library-for-python/
Example colors:
from clint.textui import colored
print 'I love ' + colored.yellow('pyt') + colored.blue('hon')
and indents too:
from clint.textui import colored, indent, puts
with indent(3, quote=colored.red(' >')):
puts ('some random text')
puts ('another text')
with indent(3, quote=colored.green(' |')):
puts('some more nested identation')
puts('cool isn\'t?')
P.S. The same author wrote a similarly nice HTTP request library called "requests": https://github.com/kennethreitz/requests
If you want a lot of control and you're on *nix, you could use the stdlib curses module.
If you just want a bit of color (/don't want to modify your script a ton to fit curses), you can use ANSI escape codes. For example:
print '\033[1;32mgreen\033[1;m'
will print the word 'green' colored... green.
Here's a loading bar I came up with using carriage returns (based on the answers in this forum):
from time import sleep
import sys
num = 100
print 'Loading: [%s] %d%%' % (' '*(num/2), 0),
try:
colorCode = 43
for x in xrange(num+1):
if x == num: colorCode = 42
print '\rLoading: [\033[1;%dm%s\033[1;m%s] %d%%' % (colorCode, "|"*(x/2), " "*(num/2-x/2), x),
sys.stdout.flush()
sleep(0.02) # do actual stuff here instead
except KeyboardInterrupt:
print '\rLoading: [\033[1;41m%s\033[1;m%s] %d%% ' % ("|"*(x/2), " "*(num/2-x/2), x)
Example Output:
Loading: [||||||||||||||||||||||||||||||||||||||||| ] 82%
(Although it doesn't show up on SO, it is colored- yellow for loading, red for abort, and green for done.)
There's a library called Urwid that offers menus and some more. I never used it for serious purposes, but the it work pretty fine with my preliminary experiences on it. It works on Un*x systems only though. (The project page says it works under Cygwin, but I never tried.)

python in terminal - how to get current colour?

I have read a couple of URLs about setting colour in terminal. But after a colour change a while later I'd like to reset into previous colour. How can I get current colour ?
(I'd like to avoid third party libraries and use only batteries included ;-))
Especially (from (python) colour printing with decorator in a function ):
import sys
green = '\033[01;32m'
red = '\033[01;31m'
... remember current colours here ...
sys.stdout.write(green+"Hello ")
sys.stderr.write(red+"world!")
You can return default color the same way you colorize your texts:
native = '\033[m'
sys.stdout.write(native)
Thus temporary coloring may be achieved with
print green + 'Hello' + native

Categories