我在理解select.select的行为时遇到了一些麻烦.请考虑以下
Python程序:
def str_to_hex(s):
def dig(n):
if n > 9:
return chr(65-10+n)
else:
return chr(48+n)
r = ''
while len(s) > 0:
c = s[0]
s = s[1:]
a = ord(c) / 16
b = ord(c) % 16
r = r + dig(a) + dig(b)
return r
while True:
ans,_,_ = select.select([sys.stdin],[],[])
print ans
s = ans[0].read(1)
if len(s) == 0: break
print str_to_hex(s)
我已将其保存到文件“test.py”.如果按如下方式调用它:
echo 'hello' | ./test.py
然后我得到了预期的行为:选择never块并打印所有数据;程序然后终止.
但如果我以交互方式运行程序,我会得到一个最不受欢迎的行为.请考虑以下控制台会话:
$./test.py
hello
[',mode 'r' at 0xb742f020>]
68
程序然后挂在那里; select.select现在再次阻止.直到我提供更多输入或关闭输入流,即使已经有字符在等待,也会打印下一个字符(以及其余所有字符)!任何人都可以向我解释这种行为吗?我在一个我编写的流隧道程序中看到了类似的东西,它破坏了整个事件.
谢谢阅读!