Get pressed key

0

I have the script that I leave below but it throws me an error when executing it on line 61:

from record import record
import os

class cliente(record):
  nombre = ""
  codigo = 0
  ultimapelicula = None
  habilitado = True

class pelicula(record):
  nombre = ""
  codigo = 0
  ultimocliente = 0
  habilitada = True

def abrirbasedatos():
  listaclientes = []
  listapeliculas = []

  ficheroclientes = abrirfichero ("Clientes.txt")
  if ficheroclientes != None:
    poblarlista(listaclientes, ficheroclientes,1)
    ficheroclientes.close()

  ficheropeliculas = abrirfichero ("Peliculas.txt")
  if ficheropeliculas != None:
    poblarlista(listapeliculas, ficheropeliculas,2)
    ficheropeliculas.close()
  return listaclientes, listapeliculas

def abrirfichero (nombrearchivo):
  try:
    return open (nombrearchivo, "r")
  except:
    print ("\n\n No se pu do abrir el fichero", nombrearchivo)
    return

def poblarlista(lista, fichero, numerolista):
    for linea in fichero:
        registro = linea.rstrip().split(",")
        if numerolista == 1:
            lista.append(cliente(nombre = registro[0], codigo = int(registro [1]), ultimapelicula = int(registro[2]), habilitado = convertirVF(registro[3])))
        elif numerolista == 2:
            lista.append(pelicula(nombre=registro [0], codigo = int(registro [1]), ultimocliente = int (registro [2]), habilitada = convertirVF(registro [3])))
    return
def convertirVF (cadena):
  if cadena == "True":
    return True
  elif cadena == "False":
    return False

def interconectarregistros():
  global listaclientes
  for c in range(len(listaclientes)):
    listaclientes[c].ultimapelicula=buscarregistro(listaclientes[c].ultimapelicula,2)
    return

def mostrarinicio():
  os.system("cls")
  print ("\n\n\n *//VIDEO CLUB// *\n")
  print ("Presione una tecla...\n\n")
  keypressed(2)
  return

def mostrarmenu(opciones,ls):
  os.system("cls")
  print (" *//VIDEO CLUB// *\n")
  print (opciones)
  return elegiropcion(ls)

def elegriopcion (limitesuperior):
  opcion = keypressed(2)
  while not opcionesvalida (opcion, limitesuperior):
    opcion = keypressed(2)
  return opcion

def opcionesvalida(opcion,ls):
  if opcion == "Escape":
    return True
  for elemento in range (1,ls + 1):
    if opcion == str(elemento):
      return True
  return False
#constantes
opcionesmenuppal = "- Menú Principal - \n\n1) Gestion de VideoClub\n2) Gestion de Peliculas\n3) Gestion de Clientes\n"
opcionesmenuclub = "- Menú VIdeoClub - \n\n1) Alquilar Pelicula\n2) Devolver Pelicula\n"
opcionesmenupelicula ="- Menú Peliculas - \n\n1) Consultar Pelicula\n2) Agregar Pelicula\n3) Eliminar Pelicula\n"
opcionesmenuclientes = "- Menú Cliente - \n\n1) Consultar Cliente\n2) Agregar Cliente\n3) Borrar Cliente\n"


# perte principal del programa
listaclientes, listapeliculas = abrirbasedatos()

mostrarinicio()

while True:
  opcionprincipal = mostarmenu (opcionesmenuppal, 3)
  if opcionprincipal == "1":
    mostarmenu(opcionesmenuclub,2)
  elif opcionprincipal == "2":
    mostrarmenu(opcionesmenupelicula,3)
  elif opcionprincipal == "3":
    mostrarmenu(opcionesmenuclientes,3)

  if opcionprincipal == "Escape":
    mostrarinicio()

This is the error that throws me:

Traceback (most recent call last):
  File "club.py", line 93, in <module>
    mostrarinicio()
  File "club.py", line 61, in mostrarinicio
    keypressed(2)
NameError: name 'keypressed' is not defined
    
asked by Marco Salazar 18.09.2017 в 03:07
source

1 answer

0

The problem is that the course is used as a programming environment PythonG .

keypressed is a functionality of the IDE (PythonG) that allows to capture the keys pressed, so it will not be of any use to you if you use another IDE to program or execute in the terminal your script.

The examples of the course are based or exposed in the book Introduction to programming with Python (Andres Marzal and Isabel Gracia, Universitat Jaume I), where the use of this IDE is explained at the beginning of chapter 3 and talks about keypressed in section B.3 . They also have the code that shows explained in the example "Management of a video store" in chapter 7.3.4.

Since it is a non-portable way to capture keystrokes, it is better to dispense with these methods. A common option is to use a input and a menu.

However, we can emulate the same behavior as keypressed without leaving the standard Python library. We can capture keystrokes using msvcrt in windows and termios in Linux:

import sys

if sys.platform == 'win32':

    import msvcrt

    def keypressed():
        key = msvcrt.getch()
        if key == b"\x1b": #ESC
            return "Escape"
        else:
            return key.decode("ANSI")

elif sys.platform == 'linux':

    import os
    import termios
    TERMIOS = termios

    def keypressed():
        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)
        key = None
        try:
            key = os.read(fd, 4)
            if key == b'\x1b':
                key = "Escape"
            else:
                key = key.decode()

        finally:
            termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
        return key

The function is called the same as in your case but without arguments:

opcion = keypressed()
  

Note : the script must be executed in the terminal / CMD for its correct operation. There is no guarantee that it works in the shell of a specific IDE.

There are many more options outside the stdlib, such as pynput , pyHook , keyboard , etc.

    
answered by 20.09.2017 в 13:04