Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard input between select() in Python

I write some codes to get the input from keyboard and also check something is alive or not:

import sys
from select import select

timeout = 10
while is_alive(): # is_alive is a method to check some stuffs, might take 5 secs
    rlist, _, _ = select([sys.stdin], [], [], timeout)
    if rlist:
        s = sys.stdin.readline()
        print repr(s)
        handle(s) # handle is a method to handle and react according to input s

I found that when the keyboard input ends outside of the waiting in select() (usually it ends during the 5 secs of is_alive()), the if rlist: will get false.

I can understand why but I don't know how to solve it.

And there is still another question related to the situation mentioned above, sometimes readline() will return the last line of my input when some inputs are located across different select() waiting.

That means, if I enter 'abc\n' and unfortunately the '\n' located outside of wating in select() (that means, when I press Enter, the program are executing other parts, such as is_alive()), and then if I enter 'def\n' and this time the Enter pressed successfully located within select(), I'll see the s from readline() becomes 'def\n' and the first line is disappeared.

Is there any good solution to solve two issues above? I'm using FreeBSD 9.0.

like image 775
justmaker Avatar asked Nov 04 '22 09:11

justmaker


1 Answers

As your code in is_alive() calls ssh, this will eat up the stdin.

Try starting ssh with the -n option or with a re-directed stdin.

The latter would work with

sp = subprocess.Popen(..., stdin=subprocess.PIPE)
sp.stdin.close()
like image 199
glglgl Avatar answered Nov 09 '22 12:11

glglgl