Откройте процесс, поймайте стандартный вывод и отправьте собственное нажатие клавиши - PullRequest
0 голосов
/ 18 сентября 2018

У меня есть этот скрипт Python (с ncurses):

#! /usr/bin/python3

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, "Last key is {}".format(k))
        stdscr.refresh()

        k = stdscr.getch()

def main():
    curses.wrapper(draw_menu)

if __name__ == "__main__":
    main()

И это мои последние попытки (с плохими результатами) перехватить стандартный вывод и отправить нажатие клавиши:

Это с Popen.

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.write('a')

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

А это другое с pexpect:

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()

Я пытался с xdotools, но не смог поймать стандартный вывод.

Есть ли какая-либо форма, чтобы обмануть / обмануть исполняемый файл для его "веры", что он работает нормально?

1 Ответ

0 голосов
/ 16 октября 2018

Я нашел решение "неблокирующее чтение stdout". Есть несколько решений в https://chase -seibert.github.io / blog / 2012/11/16 / python-subprocess-asynchronous-read-stdout.html и https://gist.github.com/sebclaeys/1232088.

И мое решение с кодом вопроса:

import os
import fcntl
import subprocess
p = subprocess.Popen(['./test5.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
fd = p.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
p.stdout.read()

p.stdin.write(b'u')
p.stdin.flush()

p.stdout.read()

p.stdin.write(b'u')
p.stdin.flush()

p.stdout.read()
p.poll()

p.stdin.write(b'q')
p.stdin.flush()

p.poll()
...