Python 如何在tty.setcbreak()之后重新打开控制台回显
我正在使用此命令禁用echo,并使用Python 如何在tty.setcbreak()之后重新打开控制台回显,python,Python,我正在使用此命令禁用echo,并使用sys.stdin.read(1) 但是,在我的程序过程中,我需要再次启用和禁用console echo。我试过了 fd = sys.stdin.fileno() old = termios.tcgetattr(fd) termios.tcsetattr(fd, termios.TCSADRAIN, old) 但这不起作用。如何优雅地启用echo ps:我使用的代码来自mizipzor 更新:代码如下: import sys import select im
sys.stdin.read(1)
但是,在我的程序过程中,我需要再次启用和禁用console echo。我试过了
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
termios.tcsetattr(fd, termios.TCSADRAIN, old)
但这不起作用。如何优雅地启用echo
ps:我使用的代码来自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)
如果你看一下这些文档,这里有一个例子: 您缺少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)
写这封信:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
没有用上面的四行来解决这个问题。@david-k-hess确切地说,我在这里发布之前尝试了这个例子。但是,我的程序中的这些行仍然不能启用echo。该示例在独立执行时运行良好。猜测与tty.setcbreak有关的内容,无法确定.tty.setcbreak不应更改回显行为-它仅控制输入处理。我猜你的程序中有一个bug。它是否太大而无法发布?或者更好的是,您是否可以将您的程序缩减到尽可能小的程度,并且仍然显示问题并发布它?我仍然不知道echo是如何被禁用的-但是,我确实在我的代码中看到了一个bug并对其进行了编辑。我刚刚检查了Python tty模块的源代码——显然,它对原始模式的解释是也关闭了ECHO,这就是它关闭的原因。
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)