2012-01-06 16 views
1

我使用這個命令來禁止回聲和使用sys.stdin.read(1)如何打開控制檯回顯在tty.setcbreak()後

tty.setcbreak(sys.stdin.fileno()) 

但是我的程序的過程中,我需要再次啓用獲取用戶輸入和禁用控制檯回聲。我試過

fd = sys.stdin.fileno() 
old = termios.tcgetattr(fd) 
termios.tcsetattr(fd, termios.TCSADRAIN, old) 

但是,沒有工作。我如何優雅地啓用回聲?

PS:我用從Python nonblocking console input代碼由mizipzor

更新:繼承人的代碼:

import sys 
import select 
import tty 
import termios 
import time 

def is_number(s): 
    try: 
     float(s) 
     return True 
    except ValueError: 
     return False 

def calc_time(traw): 
    tfactor = { 
    's': 1, 
    'm': 60, 
    'h': 3600, 
    } 
    if is_number(g[:-1]): 
     return float(g[:-1]) * tfactor.get(g[-1]) 
    else: 
     return None 
def isData(): 
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) 

old_settings = termios.tcgetattr(sys.stdin) 
try: 
    tty.setcbreak(sys.stdin.fileno()) 
    i = 0 
    while 1: 
     print i 
     i += 1 
     time.sleep(.1) 
     if isData(): 
      c = sys.stdin.read(1) 
      if c: 
       if c == 'p': 
        print """Paused. Use the Following commands now: 
Hit 'n' to skip and continue with next link. 
Hit '5s' or '3m' or '2h' to wait for 5 secs, 3 mins or 3 hours 
Hit Enter to continue from here itself. 
Hit Escape to quit this program""" 
        #expect these lines to enable echo back again 
        fd = sys.stdin.fileno() 
        old = termios.tcgetattr(fd) 
        old[3] = old[3] & termios.ECHO 
        termios.tcsetattr(fd, termios.TCSADRAIN, old) 

        g = raw_input("(ENABLE ECHO HERE):") 

        if g == '\x1b': 
         print "Escaping..." 
         break 
        if g == 'n': 
         #log error 
         continue 
        elif g[-1] in ['s','m','h']: 
         tval = calc_time(g) 
         if tval is not None: 
          print "Waiting for %s seconds."%(tval) 
          time.sleep(tval) 
        continue 

finally: 
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) 

回答

2

寫這篇:

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) 

代替上述4條線路的解決了這個問題。

3

如果你看一看的文檔,有一個例子有:

http://docs.python.org/library/termios.html#module-termios

您缺少echo標誌的設置:

old[3] = old[3] | termios.ECHO 

所以,整個事情是:

fd = sys.stdin.fileno() 
old = termios.tcgetattr(fd) 
old[3] = old[3] | termios.ECHO 
termios.tcsetattr(fd, termios.TCSADRAIN, old) 
+0

@ david-k-hess沒錯,我在這裏發佈之前試過這個例子。然而,我的程序中的這些行仍然不啓用回顯。該示例在獨立執行時可以正常工作。猜猜tty.setcbreak有些事情,無法弄清楚什麼。 – jerrymouse 2012-01-06 12:59:16

+0

tty.setcbreak不應該改變回聲行爲 - 它只控制輸入處理。我的猜測是你的程序中有一個錯誤。帖子太大了嗎? – 2012-01-06 13:03:13

+0

甚至更​​好,你可以減少你的程序儘可能小,仍然存在問題併發布? – 2012-01-06 13:09:18

相關問題