【发布时间】:2016-08-12 08:19:27
【问题描述】:
我一直在尝试(供我个人使用)一些人对定时键盘输入的解决方案,唯一有效的是 Alex Martelli/martineau here. 的一个我使用了他们的第二个代码块(从import msvcrt),它对几乎所有东西都很有用,除了比较。如果没有及时输入输入,我将 None 的返回替换为空字符串,并且我使用了一些测试行,如下所示:
import msvcrt
import time
def raw_input_with_timeout(prompt, timeout):
print prompt,
finishat = time.time() + timeout
result = []
while True:
if msvcrt.kbhit():
result.append(msvcrt.getche())
if result[-1] == '\r': # or \n, whatever Win returns;-)
return ''.join(result)
time.sleep(0.1) # just to yield to other processes/threads
else:
if time.time() > finishat:
return ""
textVar = raw_input_with_timeout("Enter here: \n", 5)
print str(textVar) # to make sure the string is being stored
print type(str(textVar)) # to make sure it is of type string and can be compared
print str(str(textVar) == "test")
time.sleep(10) # so I can see the output
在我用 pyinstaller 编译后,运行它,然后在窗口中输入 test,我得到这个输出:
Enter here:
test
test
<type 'str'>
False
我最初认为比较返回 False,因为该函数将字符附加到数组中,这可能与它没有与字符串进行正确比较有关,但在进一步研究 Python 的工作方式之后(即, SilentGhost 的回复here),我真的不知道为什么比较不会返回 True。任何回应表示赞赏。谢谢!
【问题讨论】:
-
使用
print repr(textVar),我相信会出现差异。print str("some string with unprintable bytes like \x00")在功能上等同于print "some string with unprintable bytes like \x00";两者都不会使该空字节可见(在大多数终端或控制台上)。repr()生成一个调试表示,它使用 Python 字符串文字语法为任何不可打印的内容使用转义序列创建一个 ASCII 安全的可复制值。 -
将
input转换为str不是多余的吗?input总是被解释为字符串。 -
请注意,
print已经在您尝试打印的任何内容上调用了str,这使得您所有的str()调用都是多余的,即使对于布尔和str类型的对象结果也是如此。 -
也许你有一些隐藏的空白或换行符,尝试用
textVar.strip()去掉它
标签: python python-2.7 input