描述
- 當stdin流被重定向到文件或管道時,只能獲取輸入源文本,無法再用它讀取用戶交互輸入。
- 要實現stdin接收輸入並利用console作爲用戶交互,需要使用特殊的藉口從鍵盤,而非標準輸入,直接讀取用戶輸入。python標準庫msvcrt模塊提供了該功能。
方法
控制輸入輸出( console I/O )
- msvcrt.putch(char) 用於沒有緩存地輸出一個字節型char,且不會自動換行
>>>import msvcrt
>>>msvcrt.putch(b'a')
a>>>
注意:
- 該函數接收的的字符必須是byte型
- 該函數只能接收一個字符,而非字符串
- 其輸出後不會自動換行
- msvcrt.putwch(unicode_char) 和上一個類似,唯一的區別在於msvcrt.putwch的接收範圍更大,允許接收a Unicode value
>>>import msvcrt
>>>msvcrt.putch('a')
a>>>
- msvcrt.getche() 用於讀取一個鍵盤按鍵,並且以byte型返回,但是不會在控制檯(一般是命令行)回顯。
>>>import msvcrt
>>>msvcrt.getch() #在鍵盤上按下 a
b'a'
>>>ans=msvcrt.getch() #此時,在鍵盤上按下a,console裏並不會有回顯,而是將輸入存在了ans變量裏
>>>ans
b'a'
注意:
- 輸入完成後,無需按下回車,該函數就會自動結束。
- 此方法無法讀取ctrl+c
- 若按下功能鍵,將返回其相應的轉義字符或十六進制編碼,當按下特殊的功能鍵時,會返回’\000’或者’\xe0’(python手冊裏是這樣寫的,但這個特殊的功能鍵是什麼,我還沒搞清楚)
- python手冊原文: Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return or ‘\xe0’; the next call will return the keycode. The Control-C keypress cannot be read with this function.
- msvcrt.getwch() 和上一個類似,唯一的區別在於msvcrt.getwch()的接收範圍更大,允許接收a Unicode value
- msvcrt.getche() 和 msvcrt.getch() 類似,唯一的區別在於msvcrt.getche()會將輸入回顯在console中
>>>import msvcrt
>>>msvcrt.getche() #在鍵盤上按下a
>>>ab'a' #前一個a是對輸入的回顯,b'a'是返回的結果
>>>ans=msvcrt.getche() #在鍵盤上按下a
a>>> #這裏的a是對輸入的回顯
>>>ans #查看ans的值
b'a' #結果
>>>
文件操作 file operations
待續