简体   繁体   English

Python按字符读取字符,无需打印

[英]Python Read Character by Character without printing

Am fairly new to python, We have an interesting situation. 对于python来说是一个新手,我们有一个有趣的情况。

We want to read a char from stdin, store the char, and display another char. 我们想从标准输入中读取一个字符,存储该字符,并显示另一个字符。

example: the user enters 'c', the code is expected to save 'c' and print 'v' (instantaneously) although getpass.getpass saves the input but it print nothing. 示例:用户输入'c',代码预计将保存'c'并立即打印'v',尽管getpass.getpass保存输入但不打印任何内容。 Am using Python 2.7 running on mac. 我正在使用在Mac上运行的Python 2.7。

What you're looking for is to "disable echo" in the terminal (aka TTY). 您正在寻找的是在终端(也称为TTY)中“禁用回显”。 Once you have these keywords, searching for solutions becomes a lot easier. 一旦有了这些关键字,寻找解决方案就变得容易得多。 Here's one: 这是一个:

How to turn console echo back on after tty.setcbreak() 如何在tty.setcbreak()之后重新打开控制台回显

Basically, to disable "echoing" the user's input to the screen, do this: 基本上,要禁用“回显”用户在屏幕上的输入,请执行以下操作:

import sys
import termios
import tty

old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())

After that you can use the regular functions to read from stdin and display whatever you want. 之后,您可以使用常规函数从stdin读取并显示您想要的任何内容。 Then to re-enable terminal echo: 然后重新启用终端回显:

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

Note that the above assumes you're working on a Unix-like system. 请注意,以上内容假设您正在使用类似Unix的系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM