打开一个进程并捕获stdout并发送自定义按键

2024-03-29 08:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个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()

这是我最后一次尝试捕捉stdout并发送keypress:

这与Popen有关。在

^{pr2}$

这是另一个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但我无法捕获标准输出。在

有没有任何形式的欺骗/欺骗一个可执行文件,因为它“相信”它在正常运行?在


Tags: importchildmaindefsysopentmpcurses
1条回答
网友
1楼 · 发布于 2024-03-29 08:07:38

我发现解决方案是“非阻塞读标准输出”。在https://chase-seibert.github.io/blog/2012/11/16/python-subprocess-asynchronous-read-stdout.html和{a2}中有几种解决方案。在

我的答案是:

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

相关问题 更多 >