I've tried to read one char from the console in PyCharm (without pressing enter), but to no avail.
The functions msvcrt.getch() stops the code, but does not react to key presses (even enter), and msvcrt.kbhit() always returns 0. For example this code prints nothing:
import msvcrt
while 1:
if msvcrt.kbhit():
print 'reading'
print 'done'
I am using Windows 7, PyCharm 3.4 (the same heppens in idle).
What is wrong? Is there any other way to just read input without enter?
It's possible in a special mode of the Run window.
Check the Emulate terminal in output console setting checkbox in Run/Debug Configurations
You are trying to compare <Class 'Bytes'> to <Class 'string'>.
Cast the key to a string and then compare:
import msvcrt
while True:
if msvcrt.kbhit():
key = str(msvcrt.getch())
if key == "b'w'":
print(key)
To run the program in the Command Line go to: edit Configurations > Execution > enable "Emulate terminal in output console".
This code will fix. So use key.lower()
while True:
key = msvcrt.getch()
if key == "b'w'":
print("Pressed: W without lower()")
#It won't work.
if key.lower() == "b'w'":
print("Pressed: W with lower()")
#This one will work.
#I don't know why but key.lower() works.
Related
I try to read from windows console utf-8 letters.
I have the code follows:
import codecs
sys.stdin = codecs.getreader('utf-8')(sys.stdin)
if __name__ == '__main__':
print 'query=',
query = sys.stdin.readline()
print query
But there is a strange thing:
After pressing the enter button the execution of the stdin.readline() or raw_input() or input() functions will not stop.
What do I do wrong? Or how to send eof() to stop input from console in this case?
On my Mac, hitting ^D (Ctrl-D) twice does the trick. Not sure if this will work across systems, but give it a shot.
I want my Python program to stop and wait until any key is pressed, then to print the key that was just pressed.
It's like the Pascal's command key := readkey; writeln(key);.
I' ve tried yet to use the msvcrt module and the getch command but it didn' t work. I tried this:
import msvcrt
s = msvcrt.getch()
print (s)
And it didn' t wait I pressed a key, it immediately printed b'\xff' and it ended the program
I' m working with python 3.4
Do you know any way to help me ?
I found out that if I started my .py file from the command line (pythonw) the command msvcrt.getch() didn' t work but if I save my .py file and I launched it, the command msvcrt.getch() worked correctly !
Im not sure this will be usefull for anyone but the answer to this is
s = input()
This will store the input in the "s" variable.
I want to display a long list interactively in a python command line program.
Basically, think git log, with the scrolling and the q to quit.
How would I do this in python?
The interactive view that git has is called a pager. Git just uses the pager less, or a different one if you configure it.
Basically you need to run less in a subprocess and pipe your output to it.
There are more details on how to do that in this question: Paging output from python
There is also a python helper library: https://pypi.python.org/pypi/pager (I've not used it)
Create a while loop and ask inputs from the prompt.
Eg:
import msvcrt
my_lis = range(1,78)
limit = 25
my_inp = None
while my_lis:
if my_inp != 'q':
print my_lis[:limit]
my_lis = my_lis[limit:]
else:
break
print "Press any key to continue or (q) to Quit :"
my_inp = msvcrt.getch()
# Exit
So, as the title says, I want a proper code to close my python script.
So far, I've used input('Press Any Key To Exit'), but what that does, is generate a error.
I would like a code that just closes your script without using a error.
Does anyone have a idea? Google gives me the input option, but I don't want that
It closes using this error:
Traceback (most recent call last):
File "C:/Python27/test", line 1, in <module>
input('Press Any Key To Exit')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
If you are on windows then the cmd pause command should work, although it reads 'press any key to continue'
import os
os.system('pause')
The linux alternative is read, a good description can be found here
This syntax error is caused by using input on Python 2, which will try to eval whatever is typed in at the terminal prompt. If you've pressed enter then Python will essentially try to eval an empty string, eval(""), which causes a SyntaxError instead of the usual NameError.
If you're happy for "any" key to be the enter key, then you can simply swap it out for raw_input instead:
raw_input("Press Enter to continue")
Note that on Python 3 raw_input was renamed to input.
For users finding this question in search, who really want to be able to press any key to exit a prompt and not be restricted to using enter, you may consider to use a 3rd-party library for a cross-platform solution. I recommend the helper library readchar which can be installed with pip install readchar. It works on Linux, macOS, and Windows and on either Python 2 or Python 3.
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()
msvrct - built-in Python module solution (windows)
I would discourage platform specific functions in Python if you can avoid them, but you could use the built-in msvcrt module.
>>> from msvcrt import getch
>>>
>>>
... print("Press any key to continue...")
... _ = getch()
... exit()
A little late to the game, but I wrote a library a couple years ago to do exactly this. It exposes both a pause() function with a customizable message and the more general, cross-platform getch() function inspired by this answer.
Install with pip install py-getch, and use it like this:
from getch import pause
pause()
This prints 'Press any key to continue . . .' by default. Provide a custom message with:
pause('Press Any Key To Exit.')
For convenience, it also comes with a variant that calls sys.exit(status) in a single step:
pause_exit(0, 'Press Any Key To Exit.')
Check it out.
a = input('Press a key to exit')
if a:
exit(0)
Here's a way to end by pressing any key on *nix, without displaying the key and without pressing return. (Credit for the general method goes to Python read a single character from the user.) From poking around SO, it seems like you could use the msvcrt module to duplicate this functionality on Windows, but I don't have it installed anywhere to test. Over-commented to explain what's going on...
import sys, termios, tty
stdinFileDesc = sys.stdin.fileno() #store stdin's file descriptor
oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc) #save stdin's tty attributes so I can reset it later
try:
print 'Press any key to exit...'
tty.setraw(stdinFileDesc) #set the input mode of stdin so that it gets added to char by char rather than line by line
sys.stdin.read(1) #read 1 byte from stdin (indicating that a key has been pressed)
finally:
termios.tcsetattr(stdinFileDesc, termios.TCSADRAIN, oldStdinTtyAttr) #reset stdin to its normal behavior
print 'Goodbye!'
Ok I am on Linux Mint 17.1 "Rebecca" and I seem to have figured it out, As you may know Linux Mint comes with Python installed, you cannot update it nor can you install another version on top of it. I've found out that the python that comes preinstalled in Linux Mint is version 2.7.6, so the following will for sure work on version 2.7.6. If you add raw_input('Press any key to exit') it will not display any error codes but it will tell you that the program exited with code 0. For example this is my first program. MyFirstProgram. Keep in mind it is my first program and I know that it sucks but it is a good example of how to use "Press any key to Exit"
BTW This is also my first post on this website so sorry if I formatted it wrong.
in Windows:
if msvcrt.kbhit():
if msvcrt.getch() == b'q':
exit()
In python 3:
while True:
#runtime..
answer = input("ENTER something to quit: ")
if answer:
break
You can use this code:
from os import system as console
console("#echo off&cls")
#Your main code code
print("Press Any Key To Exit")
console("pause>NUL&exit")
I am trying to get a simple curses script to run using Python (with PyCharm 2.0).
This is my script:
import curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
while 1:
c = stdscr.getch()
if c == ord('p'): print("I pressed p")
elif c == ord('q'): break
curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()
When I run this from my IDE (PyCharm 2) I get the following error:
_curses.error: setupterm: could not find terminal
Process finished with exit code 1
If I run the script from bash it will simply be stuck in the while loop not reacting to either pressing p or q.
Any help would be appreciated.
You must set enviroment variables TERM and TERMINFO, like this:
export TERM=linux
export TERMINFO=/etc/terminfo
And, if you device have no this dir (/etc/terminfo), make it, and copy terminfo database.
For "linux", and "pcansi" terminals you can download database:
http://forum.xda-developers.com/attachment.php?attachmentid=2134052&d=1374459598
http://forum.xda-developers.com/showthread.php?t=552287&page=4
Go to run/debug configuration(the one next to Pycharm run button). Sticking on Emulate Terminal In Output Console. Then you will be able to run your program with the run button.
You'll see this error if you're using Idle. It's because of Idle's default redirection of input/output. Try running your program from the command line. python3 <filename>.py
I found this question when searching for examples because I am also learning to use curses so I don't know much about it. I know this works though:
import curses
try:
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
while 1:
c = stdscr.getch()
if c == ord('p'):
stdscr.addstr("I pressed p")
elif c == ord('q'): break
finally:
curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()
I also added the try: finally: to make sure I get the terminal to it's original appearance even if something simple goes wrong inside the loop.
You have to use the addstr to make sure the text is going to be displayed inside the window.
I was having the same problem. See Curses Programming with Python - Starting and ending a curses application.
There's a curses.wrapper() function that simplifies the process of starting/ending a curses application.
Here's the example from the Python doc:
from curses import wrapper
def main(stdscr):
# Clear screen
stdscr.clear()
# This raises ZeroDivisionError when i == 10.
for i in range(0, 11):
v = i-10
stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))
stdscr.refresh()
stdscr.getkey()
wrapper(main)
If you are using macOS and running PyCharm you will have to set environment variables from the IDE itself, for execution scope.
Edit Configurations -> Environment variables
then add the below name-value pairs
TERM linux
TERMINFO /etc/zsh
The above is equivalent to exporting environment variable from the console which is done like this
$ export TERM=linux
$ export TERMINFO=/bin/zsh
the default for TERM is xterm, other values are [konsole, rxvt]
rxvt for example is often built with support for 16 colors. You can try to set TERM to rxvt-16color.
/bin/zsh is path of the terminal application that I use in mac.
It's like telling your program that you will be logging into linux(TERM) like terminal which can be found at /bin/zsh. For using bash shell it could be something like /bin/bash .