jus*_*ker 5 python select stdin readline keyboard-input
我写了一些代码来从键盘获取输入,并检查是否有效:
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
Run Code Online (Sandbox Code Playgroud)
我发现当键盘输入在等待之外select()
结束时(通常在5秒内结束is_alive()
),if rlist:
将会出现错误.
我能理解为什么,但我不知道如何解决它.
还有另一个与上述情况有关的问题,readline()
当某些输入位于不同的select()
等待时,有时会返回我输入的最后一行.
这意味着,如果我输入'abc \n'并且不幸的是'\n'位于wating之外select()
(这意味着,当我按Enter时,程序正在执行其他部分,例如is_alive()
),然后如果我输入'def \n'并且这次Enter成功定位在内select()
,我会看到s
from readline()
变为'def \n'并且第一行消失了.
解决上述两个问题有什么好的解决方案吗?我正在使用FreeBSD 9.0.
当你的代码在is_alive()
调用中时ssh
,这会耗尽标准输入。
尝试ssh
从选项-n
或重定向的stdin
.
后者将与
sp = subprocess.Popen(..., stdin=subprocess.PIPE)
sp.stdin.close()
Run Code Online (Sandbox Code Playgroud)