Python colorama not working with input?
Asked Answered
L

4

7

Finally got colorama working today, and it works excellent when printing strings, but I got the common error everyone seems to get when I attempted to use colorama with input.

Here's my code:

launch = input(Fore.GREEN + "Launch attack?(Y/N): ")

Screenshot of output:

enter image description here

Lure answered 30/9, 2015 at 17:48 Comment(6)
What OS and Python implementation are you using?Gadgetry
Did you remember to call init first?Scutate
Response to my own comment: No, I get this problem too in 3.X, even if I do init(). Works fine in 2.7 though.Scutate
Using Windows 10 64 bit Python 3.5.0Lure
Yes, I have called init without anything in it.Lure
There there was no useful answer here I filed a bugreport at github.com/tartley/colorama/issues/103Basham
M
6

I had this same issue (Python 3.5.4) and, just in case it is not too obvious for somebody else looking at this, you can always rely on the workaround of combining print / input calls where you previously had just an input call:

print(Fore.GREEN + "Launch attack?(Y/N): ", end='')
launch = input()

This should produce the exact same output as in your question, with no extra blank lines and with the code coloring working without the need of importing anything else.

The (small?) disadvantage is that you you will end up with two lines of code where you previously had just one.

Margarine answered 29/5, 2018 at 8:59 Comment(0)
U
4

On my system, input() works with colors if you add

import sphinx.quickstart

to your module.

So here is the full code.

from colorama import Fore
import colorama
import sphinx.quickstart
colorama.init()
launch = input(Fore.GREEN + "Launch attack? (Y/N): ")

(This leads to two questions:

  1. Why does it not work in the first place?
  2. What is the actual reason? – Someone might like to dive into the sphinx source code.)

N.B. if you run python via winpty from Git Bash, set convert.

colorama.init(convert=True)

Otherwise, you do not get color with the current versions.

Urge answered 4/11, 2015 at 22:0 Comment(1)
I hope this gets figured out. I would really like to use this now for a script. Importing sphinx.quickstart worked, but it added an extra 18 Megabytes to my compiled exe Python script.Czar
J
1

To get rid of this problem in the starting of the code add

import os

os.system('cls')

This will clear the screen and hence clear all the external factors blocking the colorama in input. This works 100% you just need to do it once in the starting of the program [or just before the first use of colorama with input] and after that use colorama in any creative way you want to.

I hope this will help all the creative minds trying to make their codes more colourful

Jezabella answered 27/8, 2021 at 19:16 Comment(0)
H
0

just make sure about the 'autoreset' in init()

init(autoreset=True)
Horsewoman answered 4/9, 2021 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.