我有些困惑于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
如果我选择“不阻止”,那么程序将输出所有数据并正常结束,这是预期的行为。
但是,如果我交互式地运行程序,则会发生非常不希望的情况。请看下面的控制台会话:
$ ./test.py
hello
[<open file '<stdin>', mode 'r' at 0xb742f020>]
68
该程序现在停在那里;select.select现在又被阻塞了。只有在我提供更多的输入或关闭输入流之后,下一个字符(以及其余所有字符)才会被打印出来,即使已经有字符在等待!有人能解释一下这种行为吗?我在一个流隧道程序中看到了类似的情况,它正在破坏整个事情。
感谢您的阅读!
def str_to_hex(s): return ''.join(('%02x' % ord(c) for c in s))
;-) - slowdogimport binascii; binascii.hexlify(s)
,自己写十六进制转换函数太傻了,因为已经有一个非常快的函数存在了。 - Omnifarious