原代码来自

https://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

同时支持windows和unix平台

class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix:
def __init__(self):
import tty, sys def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch class _GetchWindows:
def __init__(self):
import msvcrt def __call__(self):
import msvcrt
return msvcrt.getch() getch = _Getch()

使用的时候可以这么用,比如输入时不仅可以将输入的字符显示在屏幕上,就像是input(), 同时还可以对其每个字符都在输入时进行操作, 最后按下回车键退出输入

import sys
ss =''
while True:
s = Getch()
if s == "\r": # 注意回车键是 \r, 不是 \n
break
print(s,end='')
sys.stdout.flush() # 刷新缓冲区,不然无法显示到屏幕上
ss += s
print()
print(ss)

还可以在类中加上

def __str__(self):
return self.impl # 返回是其实是个字符串

然后使用:

str = str(_Getch())  # 自动调用__str__(self)方法

然后是我的精简魔改版

def Getch():
def _GetchUnix():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch def _GetchWindows():
import msvcrt
return msvcrt.getch() try:
impl = _GetchWindows()
except ImportError:
impl = _GetchUnix()
return impl

使用:

str = Getch()

即可


魔改精简版2

上一个代码如果把Getch()放到循环里会有个问题,就是上下左右键可以控制光标的移动,这有些惊奇,但也是我不想要的

class Getch():
def __init__(self):
try:
self.impl = self._GetchWindows()
except ImportError:
self.impl = self._GetchUnix() def __str__(self):
return self.impl def _GetchUnix(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch def _GetchWindows(self):
import msvcrt
return msvcrt.getch()

使用


import sys
ss =''
while True:
s = Getch()
s = str(Getch())
if s == "\r":
break
print(s,end='')
sys.stdout.flush()
ss += s

方法3.使用getch库

这是一个仿照windows下conio.h中的getch()函数的库

https://pypi.org/project/getch/


产生这个问题的原因是使用tcp连接通信,在终端输入一句话时,如果只输入了一半,突然接收到了对方发来的消息,就会从光标处打印在屏幕上,那么我输入的话就被打断了.

查了很多网页,不知道getch这么个东西,学C语言时压根不知道,太差了.

pyhton 下 使用getch(), 输入字符无需回车的更多相关文章

  1. linux系统下解决getch()输入数值不回显示

    在linux系统下开发C 程序却会遇到系统不支持conio.h头文件,无法使用getch()不回显函数.下面就演示如何构建函数实现数值输入不回显. #include <stdio.h> # ...

  2. 类似智能购票的demo--进入页面后默认焦点在第一个输入框,输入内容、回车、right时焦点自动跳到下一个,当跳到select时,下拉选项自动弹出,并且可以按上下键选择,选择完成后再跳到下一个。

    要实现的效果:进入页面后默认焦点在第一个输入框,输入内容.回车.right时焦点自动跳到下一个,当跳到select时,下拉选项自动弹出,并且可以按上下键选择,选择完成后再跳到下一个. PS:自己模拟的 ...

  3. ubuntu中vi下删除键和上下左右键输入字符异常(ABCD)

    刚安装的Ubuntu系统,使用vi编辑文本的时候, 出现以下现象: 点删除键输入了 D 回车无效 上下左右为字母 光标乱跳 原因: 自带的vi功能问题 解决: 卸载原有vi,重新安装完整版本vim 执 ...

  4. c 无回显读取字符/不按回车即获取字符

    最近课程设计要使用各种有趣的函数,这是其中一个 #include <conio.h> 使用方法 char c; c=getch(); 这样按下输入一个字符不按回车就ok了

  5. 终端I/O之特殊输入字符

    POSIX.1定义了11个在输入时作特殊处理的字符.实现定义了另外一些特殊字符.表18-6摘要列出了这些特殊字符. 表18-6 终端特殊输入字符 在POSIX.1的11个特殊字符中,可将其中9个更改为 ...

  6. c 语言连续输入字符型数据

    #include<stdio.h> #include<stdlib.h> void Input1(char* &str){ // /* 这种情况下想要逐个输入字符串数组 ...

  7. JNI 在命令行窗口输入字符,不显所输入字符,显指定的掩饰符

    //JNI-命令行窗口输入字符,显掩饰符.txt /*  目标:在命令行窗口输入字符,不显所输入字符,显指定的掩饰符  作者:tangshancheng@21cn.com*/ 1.KeyBoard.j ...

  8. java 图形化工具Swing 监听键盘输入字符触发动作getInputMap();getActionMap();

    双缓冲技术的介绍: 所有的Swing组件默认启用双缓冲绘图技术.使用双缓冲技术能改进频繁重绘GUI组件的显示效果(避免闪烁现象)JComponent组件默认启用双缓冲,无须自己实现双缓冲.如果想关闭双 ...

  9. ubuntu下修改mysql默认字符编码出现的Job failed to start解决办法

    ubuntu下修改mysql默认字符编码出现的Job failed to start解决办法 前几天卸掉了用了好多年的Windows,安装了Ubuntu12.04,就开始各种搭环境.今天装好了MySQ ...

随机推荐

  1. Thrift学习笔记—IDL基本类型

    thrift 采用IDL(Interface Definition Language)来定义通用的服务接口,并通过生成不同的语言代理实现来达到跨语言.平台的功能.在thrift的IDL中可以定义以下一 ...

  2. Python初学者第五天 列表及简单操作

    5day 数据类型:列表 1.创建列表 user = ['aa','14',1,10,'aa',1,2,3,3,5,9] n = [] list() m = list() 2.查询 a.按索引查询 b ...

  3. Hadoop学习---CentOS中hadoop伪分布式集群安装

    注意:此次搭建是在ssh无密码配置.jdk环境已经配置好的情况下进行的 可以参考: Hadoop完全分布式安装教程 CentOS环境下搭建hadoop伪分布式集群 1.更改主机名 执行命令:vi  / ...

  4. kivy.org - Open source Python library for rapid development of applications

    kivy.org - Open source Python library for rapid development of applicationsthat make use of innovati ...

  5. Oracle查看每小时日志切换量脚本

    ---- Show the Number of Redo Log Switches Per Hour-- SET PAUSE ONSET PAUSE 'Press Return to Continue ...

  6. Oracle三种链接方式的区别

    1 nested loops join--我们用设置statistics_level=all的方式来观察如下表连接语句的执行计划: --T2表被访问100次(驱动表访问1次,被驱动表访问100次)-- ...

  7. February 2 2017 Week 5 Thursday

    Only do what your heart tells you. 随心而行. My heart tells me that I should leave here and go back to X ...

  8. 双十一问题:kafka消费能力低下原因思考

    抛去cpu.内存等机器原因,在每个分区皆分配一个进程消费的情况下,利用扩机器来提高kafka消费速率已无能为力 此时发现,在实际洪峰时段的消费速率元达不到先前压测时的消费速率 原因思考: 1.洪峰时段 ...

  9. IntelliJ IDEA中 查看某个类中的所有方法

    方法一:alt + 7 方法二: ctrl + F12 方法三: 自定义 File Structure

  10. DVR_RDK编译报错

    报错信息: abnormal termination of /opt/dm8168/dvr_rdk/../ti_tools/cgt_dsp/cgt6x_7_3_5//bin/cmp6x make[2] ...