python getch函数_pyhton 下 使用getch(), 输入字符无需回车

原代码来自

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语言时压根不知道,太差了.

### 回答1: 在 Python 中,可以使用第三方库 `getch` 来实现从终端读取单个字符输入的操作。可以通过以下命令安装 `getch` 库: ``` pip install getch ``` 然后可以使用以下代码来读取单个字符输入: ```python import getch char = getch.getch() print(char) ``` 这将等待用户在终端中输入一个字符,并将其打印出来。需要注意的是,`getch()` 函数返回的是一个字节字符串,如果需要将其转换为 Unicode 字符串,可以使用 `decode()` 方法。 ### 回答2: Python中的getch函数用于无需回车键而直接读取用户在终端输入的单个字符。然而,Python的标准库中并没有直接提供getch函数。为了实现类似的功能,可以使用第三方库`msvcrt`或`tty`。 如果在Windows操作系统上使用Python,可以通过导入msvcrt库实现getch功能。以下是一个简单的示例代码: ```python import msvcrt def getch(): return msvcrt.getch().decode('utf-8') # 测试 print("请输入一个字符:") char = getch() print("您输入字符是:", char) ``` 如果在类Unix系统(如Linux和Mac)上使用Python,则可以导入tty库来实现getch功能。以下是一个类似的示例代码: ```python import tty import sys import termios def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) char = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return char # 测试 print("请输入一个字符:") char = getch() print("您输入字符是:", char) ``` 这些代码示例中,我们定义了一个名为getch函数来获取用户在终端上输入的单个字符。在函数内部,我们使用msvcrt.getch()函数和tty.setraw()函数来实现这一功能。最后,我们通过调用getch函数来读取用户输入字符,并打印出来。 这样,我们就可以在Python代码中实现类似于getch的功能,以便在终端中读取单个字符的用户输入。 ### 回答3: `getch`是Python中的一个库,用于从键盘获取单个字符输入,而无需按下回车键。它是通过对终端的输入模式进行修改来实现这一功能的。 这个库的用途非常广泛。它可以用于创建用户界面,处理游戏输入,以及其他一些需要实时获取用户输入的应用程序。 在使用`getch`之前,我们需要先安装它。可以使用以下命令来安装: ``` pip install getch ``` 一旦安装完成,就可以在Python代码中使用`getch`了。下面是一个简单的例子,展示了如何使用`getch`来获取用户输入字符: ```python import getch def main(): char = getch.getch() print(f"你输入了:{char}") if __name__ == "__main__": main() ``` 运行这段代码后,程序会等待用户输入一个字符,然后将输入字符打印出来。 需要注意的是,`getch`函数在不同的操作系统上行为可能会有所不同。在某些操作系统上,它只能获取ASCII字符,而无法获取特殊字符或功能键。如果需要处理特殊字符或功能键,可能需要使用其他第三方库或方法来实现。 总之,`getch`是Python中一个方便的库,用于从终端获取单个字符输入。通过使用该库,我们可以轻松地编写需要实时获取用户输入的应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值