EzDevInfo.com

colorama

Simple cross-platform colored terminal text in Python

How to Install Colorama, Python

I downloaded the colorama module for python and I double clicked the setup.py. The screen flashed, but when I try to import the module, it always says 'No Module named colorama'

I copied and pasted the folder under 'C:\Python26\Lib\site-packages' and tried to run the setup from there. Same deal. Am I doing something wrong?

Thanks, Mike


Source: (StackOverflow)

Annoying spaces that won't disappear. What should I do?

I am currently making a game with Python.

I want the code to read:

[00:00:00]   Name|Hello!

Here is my code:

print(Fore.YELLOW + Style.BRIGHT + '['),
print strftime("%H:%M:%S"),
print ']',
print(Style.BRIGHT + Fore.RED + ' Name'),
print(Fore.BLACK + '|'),
print(Fore.WHITE + Style.DIM + 'Hello!')
time.sleep(5)

Instead - for some reason - it becomes like this:

[ 00:00:00 ]    Name | Hello!

I have no idea what's wrong with this code, or how to fix it.

I would really appreciate all the help I can get! Thank you.


Source: (StackOverflow)

Advertisements

How do I allow cxfreeze to import colorama?

I'm incredibly new, and I was wondering if I could package colorama with cx_freeze, I've seen some people with a similar question yet I completely do not understand how to specifically choose colorama. Please, explain like I'm 10 years old. This is the coding in my setup.py file for cx_freeze:

from cx_Freeze import setup, Executable``
setup(name = "popcarventure" ,
      version = "0.1" ,
      description = "" ,
      executables = [Executable("TheAdventure.py")])

Can you please post how to specifically import colorama? Much appreciated! Note: I am using python 3.4 on windows, not python 2.


Source: (StackOverflow)

Coloring text in terminal according to part of speech

I'd like to color the sentence in terminal so that nouns will be blue and verbs will be green. Everything else will be black.

So far, i tried to use nltk and colorama modules for this purpose.

import nltk
from colorama import Fore

This code will find out the nouns and verbs, so that verbs are VB or VBD and nouns are NN.

s = nltk.word_tokenize(sample_sentence)
tagged_text = nltk.pos_tag(s)
print tagged_text

[('Stately', 'RB'), (',', ','), ('plump', 'VB'), ('Buck', 'NNP'), ('Mulligan', 'NNP'), ('came', 'VBD'), ('from', 'IN'), ('the', 'DT'), ('stairhead', 'NN'), (',', ','), ('bearing', 'VBG'), ('a', 'DT'), ('bowl', 'NN'), ('of', 'IN'), ('lather', 'NN'), ('on', 'IN'), ('which', 'WDT'), ('a', 'DT'), ('mirror', 'NN'), ('and', 'CC'), ('a', 'DT'), ('razor', 'NN'), ('lay', 'NN'), ('crossed', 'VBD'), ('.', '.')]

When I want to print colored text I will use:

print Fore.BLUE + some_noun
print Fore.GREEN + some_verb
print Fore.BLACK + something_else

I have a problem to print the sentence. How would you loop through tagged_text so that it will print the sample_sentence unchanged (only the desired colors will be applied)?


Source: (StackOverflow)

Colorama AssertionError in Python 3.2

I've recently started using Python 3.2 and have never attempted programming before. I copied the colorama folder to the lib directory in C:\Python32\lib and then made the following code in my attempt at a text-based adventure game:

 import colorama
    from colorama import Fore, Back, Style
    colorama.init()

    notedaction = "You have gained a SWORD AND SHIELD!"
    uniqueskill = "strength"

        if 'strength' in uniqueskill.lower():
           time.sleep(3)
           print('As you are a Warrior, I shall supply you with the most basic tools every Warrior needs.')
           time.sleep(3)
           print('A sword and shield.')
           time.sleep(1)
           print(Fore.RED + notedaction)

However, whenever I reach this section of code, I am given the following error:

  File "<pyshell#10>", line 7, in <module>
    print(Fore.RED + notedaction)
  File "C:\Python32\lib\colorama\ansitowin32.py", line 34, in write
    self.__convertor.write(text)
  File "C:\Python32\lib\colorama\ansitowin32.py", line 115, in write
    self.write_and_convert(text)
  File "C:\Python32\lib\colorama\ansitowin32.py", line 140, in write_and_convert
    self.convert_ansi(*match.groups())
  File "C:\Python32\lib\colorama\ansitowin32.py", line 154, in convert_ansi
    self.call_win32(command, params)
  File "C:\Python32\lib\colorama\ansitowin32.py", line 175, in call_win32
    func(*args, **kwargs)
  File "C:\Python32\lib\colorama\winterm.py", line 48, in fore
    self.set_console(on_stderr=on_stderr)
  File "C:\Python32\lib\colorama\winterm.py", line 68, in set_console
    win32.SetConsoleTextAttribute(handle, attrs)
  File "C:\Python32\lib\colorama\win32.py", line 66, in SetConsoleTextAttribute
    assert success
AssertionError

Any ideas on what is wrong?


Source: (StackOverflow)

Python, Colorama, assign color code to variable

I have changed the colors of Python console using the following code:

from colorama import init
init()
from colorama import Fore, Back, Style
print(Fore.COLORNAME)

But I have to set COLORNAME myself, like this:
print(Fore.RED)

What I'm trying to do is to make COLORNAME as variable, so that I can change from somewhere else, I wanna make it something like this:

COLORNAME = 'RED'
print(Fore.COLORNAME)

and the test should be printed as RED, but I'm getting this error:
'AnsiCode object has no attribute str'
because this:
COLORNAME = 'RED'
mean I'm assigning a string to the variable COLORNAME.
Any ideas please? Thank you.

Windows 8, 64bit, Python 2.7


Source: (StackOverflow)

How can I make Python with Colorama print coloured text after compiling it to an .exe?

I'm using Python 2.7 with colorama 0.2.5. I'm calling a method, that prints some coloured text:

from colorama import Fore
from colorama import Style
from colorama import init


    def sendData(self):
        print("Sending data..."),
        sys.stdout.flush()
        self.browser.submit()
        print(Style.BRIGHT + "[ " + Fore.GREEN + "OK" + Fore.RESET + " ]" + Style.RESET_ALL) ## Prints coloured text

init()
sendData()

This part of code gives the user some terminal output in a GUI application (made with pyqt).

Running this script by using the Python interpreter works the way it should on both Ubuntu 12.04 and Windows 7. However, when I compile it to one executable file using PyInstaller (using the --onefile flag), things change:

  • On Ubuntu 12.04, when running the executable from a Terminal, I'm getting coloured terminal output, the way I want it to be.
  • On Windows 7, when running the executable from cmd, the GUI runs fine, but I'm not getting terminal output.

If it helps, the flags I give along with the PyInstaller command are -F (one-file) and -w (windowed mode).

How can I get the executable to print coloured text in cmd in Windows 7?


Source: (StackOverflow)

Tee does not show output or write to file

I wrote a python script to monitor the statuses of some network resources, an infinite pinger if you will. It pings the same 3 nodes forever until it receives a keyboard interrupt. I tried using tee to redirect the output of the program to a file, but it does not work:

λ sudo ./pingster.py

15:43:33        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:35        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:36        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:37        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:38        node1 SUCESS | node2 SUCESS | node3 SUCESS
^CTraceback (most recent call last):
  File "./pingster.py", line 42, in <module>
    main()
  File "./pingster.py", line 39, in main
    sleep(1)
KeyboardInterrupt

λ sudo ./pingster.py | tee ping.log
# wait a few seconds
^CTraceback (most recent call last):
  File "./pingster.py", line 42, in <module>
    main()
  File "./pingster.py", line 39, in main
    sleep(1)
KeyboardInterrupt

λ file ping.log
ping.log: empty 

I am using colorama for my output, I thought that perhaps could be causing the issue, but I tried printing something before I even imported colorama, and the file is still empty. What am I doing wrong here?

Edit: Here is the python file I'm using

#!/home/nate/py-env/ping/bin/python

from __future__ import print_function
from datetime import datetime
from collections import OrderedDict
from time import sleep

import ping
import colorama


def main():
    d = {
        'node1': '10.0.0.51',
        'node2': '10.0.0.50',
        'node3': '10.0.0.52',
    }
    addresses = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

    colorama.init()
    while True:
        status = []
        time = datetime.now().time().strftime('%H:%M:%S')
        print(time, end='\t')
        for location, ip_address in addresses.items():
            loss, max_time, avg_time = ping.quiet_ping(ip_address, timeout=0.5)
            if loss < 50:
                status.append('{0} SUCESS'.format(location))
            else:
                status.append(
                    '{}{} FAIL{}'.format(
                        colorama.Fore.RED,
                        location,
                        colorama.Fore.RESET,
                    )
                )
        print(' | '.join(status))
        sleep(1)

if __name__ == '__main__':
    main()

Source: (StackOverflow)

Colorize Terminal Text with Typewriter effect in Python

I am currently using python 2.7, and I am having a little bit of trouble coding this idea I have. I know it is easy enough to color text in the terminal in python 2.7 with libraries like colorama or termcolor, but these methods don't quite work in the way I am trying to use.

You see, I am trying to create a text based adventure game, that not only has colored text, but also gives a quick typewriter-style effect when doing so. I have the typewriter effect down pat, but anytime I try to integrate it with a colorizing library the code fails, giving me the raw ASCII character instead of the actual color.

import sys
from time import sleep
from colorama import init, Fore
init()

def tprint(words):
for char in words:
    sleep(0.015)
    sys.stdout.write(char)
    sys.stdout.flush()

tprint(Fore.RED = "This is just a color test.")

If you run the code, you will see that the typewriter effect works, but the color effect does not. Is there any way I can "embed" the color into the text so that sys.stdout.write will show the color with it?

Thank You

EDIT

I think I may have found a workaround, but it is kind of a pain to change the color of individual words with this method. Apparently, if you use colorama to set the ASCII color before you call the tprint function, it will print in whatever the last set color was.

Here is the example code:

print(Fore.RED)
tprint("This is some example Text.")

I would love any feedback/improvements on my code, as I would really like to find a way to call the Fore library within the tprint function without causing ASCII errors.


Source: (StackOverflow)

Colorama and spacing

I have a class to print "TextBoxes" that look similar to

#========================================#
|                                        |
|                                        |
|                                        |
|                                        |
|                                        |
#========================================#

When given dimensions. You can then assign lines text by calling the method setLineText. Each line is stored in a list and printed with the method render with a simple for loop.

Everything works fine and dandy until I introduce Colorama to the mix, when I use my setLineText method with any Colorama formatting the line that I changed will always be short 5 spaces per call I used for formatting

For example,

MainBox = views.TextBox(35, 6)
MainBox.setLineText(1, "Hello! " + Fore.RED + User.name + Fore.RESET)
MainBox.Render()

will output

#=================================#
| Hello! User           |
|                                 |
|                                 |
|                                 |
#=================================#

My question is, is there a way to avoid prevent this from happening?

EDIT: As an extra note, I'm using windows.

ANSWER: After tons of testing, any regex I could come up with didn't work. My solution is to just use sys.stdout.write() to print the color changes and resets. It works well and hardly even need to change my current code


Source: (StackOverflow)

Py2exe; Import Error no module named colorama

My python script is using colorama module. So, I include it and try to compile but I get this error:

raise ImportError, "No module named " + qname
ImportError: No module named colorama

My setup.py is this one:

from distutils.core import setup
import py2exe
import colorama

setup(console=['sniffer_4_0.py'],options={"py2exe": {'includes': ["email.utils", "colorama"]}})

I have seen someone who had the same problem (with another library, not colorama) and solved it by importing that library at the beggining of the script. So it's what I did, but I have the same error. Do you know why?

Thanks! Maichel


Source: (StackOverflow)

Move cursor up using Colorama has problems at bottom of screen

I'm using Colorama in Python (32-bit 2.7.2) on Windows 7 (64-bit) and it works great for colouring text in the console, but I'm having problems when getting it to move the cursor.

Specifically, if I use the ANSI code to go up a line, it works when the cursor is far from the bottom of the screen, but when the cursor is near the bottom the cursor doesn't move up correctly and then text starts to be printed further down the page causing it to scroll.

The code I use to move up a line is:

sys.stdout.write('\x1b[4A')

where 4 is moving it four lines up (and something like '\x1b[8A' would move it eight lines up)

I'm not sure if this is a lack of understanding on my part regarding how ANSI codes work or whether it is an issue with Colorama.

To recreate it, run something like this in either the normal Windows Command Prompt (cmd.exe) or in Console2 (it seems to make no difference)

from __future__ import print_function
import colorama
from colorama import Fore, Back, Style
import sys

def main():

    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    print('Blah')
    sys.stdout.write('\x1b[6A')
    sys.stdout.write('some text')

if __name__ == '__main__':
    main()

If you run the code above near the top of the screen, it'll end up with "some text" written part way through the "Blah" output, but if you start it when already near the bottom of the screen the "some text" will be at the end, with the cursor seemingly not having scrolled back at all.

I specifically need to move the cursor up, so it's placed on a relative basis to other output, rather than give it an absolute screen position (ie move it to position x,y)

Any suggestions on where to start?


Source: (StackOverflow)