【问题标题】:Open a process and catch stdout and send custom keypress打开一个进程并捕获标准输出并发送自定义按键
【发布时间】:2018-09-18 00:05:14
【问题描述】:

我有这个 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,但无法捕捉到标准输出。

是否有任何形式可以欺骗/欺骗可执行文件,让其“相信”它正在正常运行?

【问题讨论】:

  • 你在解决什么样的问题?
  • 谢谢,这是个好问题。有一个很好的旧开源游戏(它是用 ncurses 制作的)。我想或至少尝试包装这个游戏,并用 Godot 为这个游戏做一个前端。我正在尝试制作一个脚本来解析标准输出并发送密钥。

标签: python popen pexpect xdotool


【解决方案1】:

我发现解决方案是“非阻塞读取标准输出”。 https://chase-seibert.github.io/blog/2012/11/16/python-subprocess-asynchronous-read-stdout.htmlhttps://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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多