[Python-es] ¿pexpect se puede capturar la salida de un ejecutable con ncurses? ¿Y enviar las pulsaciones de teclado?

Miguel de Dios Matias tres.14159 en gmail.com
Lun Sep 24 10:30:14 EDT 2018


Buenas.

Ando pegándome en intentar "encapsular" un ejecutable (un viejo roguelike)
que saca la salida en ncurses y se interacciona con pulsaciones de teclado.

Me he hecho un script sencillo en ncurses para probar (este espera la
pulsación y muestra la tecla pulsada y si es q se sale).

----
import sys,os
import curses

def draw_menu(stdscr):
   k = 0
   while (k != ord('q')):
      stdscr.clear()
      height, width = stdscr.getmaxyx()
      stdscr.addstr(0, 0, "HOLA {}".format(k))
      stdscr.refresh()

      k = stdscr.getch()

def main():
   curses.wrapper(draw_menu)

if __name__ == "__main__":
   main()
----

Y he probado con popen, pexpect y me falta sacrificar una cabra...no lo
saco, aquí mis intentos infructuosos:

----

"""
ps -A | grep cata
xdotool search --pid 3819
xdotool key --window 50331670 q
"""

"""
from subprocess import Popen, PIPE

#p = Popen('./test5.py', stdin=PIPE, stdout=PIPE, shell=True)
#p = Popen('./test5.py', shell=True)
p = Popen('./test2.py')

print(p.pid)

sleep(100)

# p.stdin.close()
# p.stdout.close()
# p.wait()

"""


# ~ import pexpect

# ~ child = pexpect.spawn("./test5.py")
# ~ child.send('a')
# ~ child.send('b')
# ~ child.interact()


# ~ import sys
# ~ import pexpect
# ~ child = pexpect.spawn('./test5.py', logfile=open("/tmp/file", "wb"))
# ~ child.logfile = open("/tmp/file", "wb")
# ~ child.expect(pexpect.EOF)
# ~ child.send('a')
# ~ child.send('q')
# ~ child.interact()

"""
https://stackoverflow.com/questions/2575528/simulating-key-press-event-using-python-for-linux
spawn
fout = file('output.txt', 'w') child.logfile = fout
"""

import sys
from time import sleep
import pexpect
child = pexpect.spawn('./test5.py')
child.logfile = open("/tmp/file", "wb")
sleep(2)
child.send('a')
print(child.read())
# ~ child.send('q')
----

Por si alguien le interesa el karma en stackoverflow, tengo la misma
pregunta por allí, si contesta le voto positivo:

https://stackoverflow.com/questions/52377179/open-a-process-and-catch-stdout-and-send-custom-keypress

Y también por si alguno le ha picado la curiosidad tengo también un mensaje
en el foro de referencia de videojuegos libres:

https://forum.freegamedev.net/viewtopic.php?f=3&t=8113&sid=47af7f6dfc9848160f9ca27791a045f1

Saludos.
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://mail.python.org/pipermail/python-es/attachments/20180924/ec33c415/attachment.html>


Más información sobre la lista de distribución Python-es