问题
Using pexpect I'm running Python in a subprocess. When the program below is run, I have to hit a key before the >>>
prompt is displayed.
I previously was using a naive version of pexpect, but switched hoping this would fix the problem. In this naive version, the problem was that select.select()
returned stdin as ready to read when in fact it wasn't, as a blocking read on stdin was attempted, blocking the program until I hit a key. I suspect the same thing is happening here.
How do I prevent this behavior?
This is as minimal a working example as I've been able to come up with so far:
import socket
import sys
import threading
import termios
import tty
import pexpect
def get_cursor_position(to_terminal, from_terminal):
original_stty = termios.tcgetattr(from_terminal)
tty.setcbreak(from_terminal, termios.TCSANOW)
try:
query_cursor_position = "\x1b[6n"
to_terminal.write(query_cursor_position)
to_terminal.flush()
while from_terminal.read(1) != 'R':
pass
finally:
termios.tcsetattr(from_terminal, termios.TCSANOW, original_stty)
def set_up_listener():
def get_cursor_on_connect():
conn, addr = sock.accept()
get_cursor_position(sys.stdout, sys.stdin)
conn.send(b'done')
conn.close()
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 1234))
sock.listen(1)
t = threading.Thread(target=get_cursor_on_connect)
t.start()
if __name__ == '__main__':
if len(sys.argv) == 2 and sys.argv[1] == 'inner':
s = socket.socket()
s.connect(('localhost', 1234))
assert b'done' == s.recv(1024)
sys.stderr.write('>>> ')
sys.stderr.flush()
while True:
pass # spin forever so daemon thread doesn't die
else:
set_up_listener()
proc = pexpect.spawn(sys.executable, ['test.py', 'inner'])
proc.interact()
来源:https://stackoverflow.com/questions/29663269/print-delay-with-pexpect-select-returning-stdin-when-no-data-ready-to-read