Python Forum
Advance program when certain keys are pressed? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Advance program when certain keys are pressed? (/thread-18477.html)



Advance program when certain keys are pressed? - Chrislw324 - May-19-2019

I'm trying to build a program that will quiz me on vim commands.
As of now, the program works, but I have to press enter after entering the command. Such as:

move down (I press "j" then "enter")
move to top of screen (I press "e" then "enter")
move forward to end of word (I press "e" then "enter")

Is there a way to advance the program without having to hit enter?


I have the questions and answers in a csv file
Here's the program I have:

#! /usr/bin/python3

import csv
from functions import clearScreen


clearScreen() # clearing the screen
studySet = input("Enter the set you would like to study: ")
with open(studySet) as f:     # opening the csv file that contains the questions/answers
	fileContents = csv.reader(f)
	flashcards = {rows[0]:rows[1] for rows in fileContents} # storing the contents of the csv file into a dictionary
questions = []
answers = []
for eachKey in flashcards.keys(): # this and next line storing the keys of dict in list called questions
	questions.append(eachKey)
	answers.append(flashcards[eachKey])
clearScreen()
counter = 0
while counter < len(questions):
	yourAnswer = input(questions[counter] + "\n")
	if yourAnswer == answers[counter]:
		clearScreen()
	elif yourAnswer != answers[counter]:
		clearScreen()
	    print("Sorry. That was not correct.")
		print("The correct answer is " + answers[counter])
		questions.append(questions[counter])
		answers.append(answers[counter])
	counter += 1

clearScreen()



RE: Advance program when certain keys are pressed? - SheeppOSU - May-19-2019

Look into the import keyboard


RE: Advance program when certain keys are pressed? - woooee - May-19-2019

Quote:Is there a way to advance the program without having to hit enter?
You will have to use a third party (does come with Python) module. One module is termios
import termios, sys, os
TERMIOS = termios
def getkey():
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
    new[6][TERMIOS.VMIN] = 1
    new[6][TERMIOS.VTIME] = 0
    termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
    c = None
    try:
        c = os.read(fd, 1)
    finally:
        termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
    return c
if __name__ == '__main__':
    print("type something...'q' to quit")
    s = ''
    while 1:
        c = getkey()
        if c == 'q':
            break
        print("captured key", c, ord(c))
        s = s + str(c)

    print(s)