Python colorama not working with input? - python-3.x

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:

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.

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:
Why does it not work in the first place?
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.

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

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

Related

Module 'pygame.locals' has no 'QUIT' Python 3.8.2 Pygame [duplicate]

When importing pygame pylint is going crazy:
E1101:Module 'pygame' has no 'init' member
E1101:Module 'pygame' has no 'QUIT' member
I have searched the net and I have found this:
"python.linting.pylintArgs": ["--ignored-modules=pygame"]
It solves the problem with pygame, but now pylint is going crazy in other way: crazy_pylint.png.
Then I have found "python.linting.pylintArgs": ["--ignored-files=pygame"], but what it does is completely disabling pylint for the whole directory I am working in.
So how do I say pylint that everything is OK with pygame?
For E1101:
The problem is that most of Pygame is implemented in C directly. Now, this is all well and dandy in terms of performance, however, pylint (the linter used by VSCode) is unable to scan these C files.
Unfortunately, these same files define a bunch of useful things, namely QUIT and other constants, such as MOUSEBUTTONDOWN, K_SPACE, etc, as well as functions like init or quit.
To fix this, first things first, stop ignoring the pygame module by removing all your arguments in "python.linting.pylintArgs". Trust me, the linter can come in handy.
Now to fix the problems. For your constants (anything in caps), manually import them like so:
from pygame.constants import (
MOUSEBUTTONDOWN, QUIT, MOUSEMOTION, KEYDOWN
)
You can now use these without prepending them with pygame.:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == KEYDOWN:
# Code
Next, for your init and other functions errors, you can manually help the linter in resolving these, by way of 2 methods:
Either add this somewhere in your code: # pylint: disable=no-member. This will deactivate member validation for the entire file, preventing such errors from being shown.
Or you can encase the line with the error:
# pylint: disable=no-member
pygame.quit()
# pylint: enable=no-member
This is similar to what the first method does, however it limits the effect to only that line.
Finally, for all your other warnings, the solution is to fix them. Pylint is there to show you places in which your code is either pointless, or nonconforming to the Python specs. A quick glance at your screenshot shows for example that your module doesn't have a docstring, that you have declared unused variables...
Pylint is here to aid you in writing concise, clear, and beautiful code. You can ignore these warnings or hide them (with # pylint: disable= and these codes) or spend a little time cleaning up everything.
In the long run, this is the best solution, as it'll make your code more readable and therefore maintainable, and just more pleasing to look at.
For a specific binary module you can whitelist it for pylint. For the pygame module it would be as follows:
{
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=pygame"
]
}
OP You can also maintain the pylint pygame fix you found in vscode by including the vscode default arguments yourself.
The linter is going nuts (crazy_pylint.png) because you were clobbering the default pylint arguments with your own custom python.linting.pylintArgs.
The pygame module ignore fix does work, and the linter can return to non-crazy mode by also including the clobbered default arguments in your own custom python.linting.pylintArgs.
From the docs:
These arguments are passed whenever the python.linting.pylintUseMinimalCheckers is set to true (the default).
If you specify a value in pylintArgs or use a Pylint configuration file (see the next section), then pylintUseMinimalCheckers is implicitly set to false.
The defaults vscode passes according to this: https://code.visualstudio.com/docs/python/linting are:
--disable=all,
--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode
So, here is how to pass all those defaults as well as the --ignored-modules=pygame in user settings within vscode:
"python.linting.pylintArgs": [
"--disable=all",
"--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode",
"--ignored-modules=pygame"
]
Per #C._ comment above, he's definitely speaking truth; the linter will help!
I'm writing better code with it enabled for sure.
Also, I discovered that you can further fine-tune your pylinter with the enable line and comma delimited "readable pylint messages"
listed here: https://github.com/janjur/readable-pylint-messages/blob/master/README.md
So to not ignore also trailing-newlines, you would append the enable= list argument to include simply trailing-newlines.
I really hope this helps you OP :) It helped me!
Thanks for asking the question, and sharing --ignored-modules.

I'm trying to use the turtle methods, etc. listed on the official python page but I keep getting errors

I'm using turtle to create a video game.
I'm making this program for a virtual class, and I don't know the exact limitations of the (online) IDLE provided. I'm not currently able to test my code in any other environment. I don't want to use pygame or anything because I don't know if I can and also I don't want to rewrite a bunch of my code.
The problems I'm having are mostly with the TurtleScreen/Screen. I can't call .Screen() or .TurtleScreen(), .bgcolor(), .turtlesize(), and probably a lot more I haven't checked yet. Here's an example:
bg = turtle.Screen()
turt = turtle.Turtle()
bg.bgcolor("black")
I just receive a
ParseError: bad input
when I run it. Any input is much appreciated!
A parse error usually comes from python being unable to parse your code rather than an issue with Turtle.
The code snippet you posted above works fine so the problem is likely with some other lines of code that precede it. Double check your syntax on lines before the error occurs and make sure there aren't any missing parenthesis, brackets, quotes, etc that would impact later lines.

How to open program with key input

I want to open the calculator program when I type "Open calculator " . I researched a lot , but didn't get the answer I wanted.Can anyone please answer my question.
There are 2 ways to do this. One way would be access the cmd using Python which can be done by using os module. When you try to open the calculator from your command prompt, you probably type calc. Instead of manually doing this, you can have your Python code do it for you, this is how:
import os
os.system('calc')
The second way is very similar to the first one, except that this method opens another command prompt window so the window in which you're running the python code is not disturbed.
import subprocess
subprocess.Popen("calc",stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,shell=True)

hidding the runfile() command in Spyder

Is there a way to 'hide' the runfile() command so that it doesn't get displayed on the IPython console? It can get really annoying when the file has a long path since it displays the path twice:
runfile('C:/Users/One/Desktop/Training/Week1/Files/file1.py',wdir='C:/Users/One/Desktop/Training/Week1/Files/file1.py')
I agree with you, I hate having a cluttered IPython console .
I found a way while I was trying to find a solution to clear the old text in the console when starting a script:
Define an anonymous function (reference: https://python-forum.io/Thread-Difference-between-os-system-clear-and-os-system-cls) at the beginning of your script to clear the console from text
cls = lambda: print("\033[2J\033[;H", end='')
cls()
The annoying runfile (...) text section will disappear :)
(Spyder maintainer here) This is not possible in our current stable version (Spyder 4), sorry.
This is how I made Alexis' idea work reliably for me. My screen got updated by my code before cls() finished executing, consequently it was blanked over.
from time import sleep
def cls():
print("\033[2J\033[;H", end='')
sleep(0.1)
cls()

Sympy - print(limit()) as latex

Probably this is a question easy to answer but I couldn't find any solution that worked for me. I want to have the content of print() to be displayed as latex.
Edit: I'm using jupyter.
import sympy
from sympy.assumptions import assuming, Q
sympy.init_printing()
K,L,alpha = sympy.symbols("K,L,alpha")
Y = (K**alpha)*(L**(1-alpha))
Y
with assuming(Q.is_true(L == 1)):
print(sympy.limit(Y,K,1,"-"))
sympy.limit(1/alpha,L,0)
For the calculation without assumption (last code line) everything works fine.
I have already tried latex(print()) but that only gave me latex code but no latex output.
Best,
Fabian
You could do the following. Insert at the beginning of the code
from IPython.display import display
and replace print(...) with display(...), e.g.,
display(sympy.limit(Y,K,1,"-"))
Finally I used the following solution:
sympy.limit(Y.subs(L,1),K,1,"-")
Easy and works fine ...

Resources