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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With