我一直在嘗試(爲我自己的個人使用)一些人的定時鍵盤輸入的解決方案,唯一一個工作是由亞歷克斯Martelli/martineau here.我用他們的第二個代碼塊(從導入msvcrt開始)除了比較之外,它幾乎適用於所有的事情。我取代無用空字符串的返回,如果沒有輸入在時間上被輸入並予使用的一些測試線如下所示:這些字符串是怎麼來的?
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,運行它,和類型的測試到窗口,我得到這樣的輸出:
Enter here:
test
test
<type 'str'>
False
我原本以爲比較中返回false,因爲函數將字符數組,可能已經有一些東西,用它做不是做一個字符串一個適當的比較,但經過進一步觀察Python的工作方式(即SilentGhost的響應here),我真的不知道爲什麼比較ison不會返回True。任何迴應表示讚賞。謝謝!
使用'print repr(textVar)',我相信會出現差異。 'print str(「一些帶有不可打印字節的字符串,例如\ x00」)在功能上等同於'print'一些帶有不可打印字節的字符串,例如\ x00「';也不會使該空字節可見(在大多數終端或控制檯上)。 'repr()'產生一個*調試表示*,一個使用Python字符串文字語法爲任何不可打印的東西使用轉義序列創建一個ASCII安全的可重現值。 –
將'input'轉換爲'str'不是多餘的嗎? 'input'總是被解釋爲字符串。 – Ian
請注意,'print'已經在你試圖打印的任何東西上調用'str',使得所有'str()'調用都是冗餘的,即使是布爾類型和str類型的對象結果也是如此。 –