[英]curses getch() returns different values for the main window and pads in python
[英]Python curses getch() always returns -1 if data is piped to my program
我想讀取通過管道傳輸到我的程序中的數據,然后使用 curses 獲取用戶輸入。 我有以下代碼:
import curses
import sys
import select
def read_piped_data():
data = ""
while(sys.stdin in select.select([sys.stdin,],[],[],0.0)[0]):
x = sys.stdin.read(1)
if(len(x) == 0): break
data += x
sys.stdin = open("/dev/tty")
return (data if len(data) > 0 else None)
def main(stdscr):
data = read_piped_data()
if(data != None): do_something1(data)
curses.raw()
stdscr.keypad(True)
stdscr.timeout(0)
while(True):
ch = stdscr.getch()
if(ch == -1): continue
if(not do_something2(stdscr,ch)): break
curses.wrapper(main)
當我使用以下命令執行上述操作時:
$ python3 test.py
一切正常: do_something1()
沒有被調用,但是do_something2()
每當我按下任何鍵時都會被調用。 但是當我 pipe 的東西為:
$ ls | python3 test.py
我的代碼失敗: do_something1()
被調用,它正確處理管道數據,但do_something2()
從未被調用,我的程序基本上處於無限循環中,沒有注冊任何按鍵!
保留或刪除sys.stdin = open("/dev/tty")
無效。 在另一個 stackoverflow 答案中,我發現這個解決方案可以使 input() 工作(從管道讀取后)。 盡管在我重新分配標准輸入后 input() 可以工作,但 getch() 不能。
即使我不讀取管道數據,只需將一些命令管道傳輸到我的程序就足以使 curses getch() 無法讀取任何按鍵。
我在 Ubuntu 20.04 上使用帶有 Python 3.8 的詛咒。 從 pipe 讀取后,如何“重新激活”curses 中的輸入?
也許是因為標准輸入不能保證是可分配的? 在 C,我對此沒有任何問題:
freopen("/dev/tty","r",stdin);
用 fopen 重新分配也在這里工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.