Python getch

有时候我们需要用户的输入,但不需要回车。比如贪吃蛇这类的小游戏,我们不需要每移动一次就回车一次。

源代码来自https://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

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()

但是这会有个问题,就是输入 a 会出现 b’a’

虽然这里也有一篇文章讲过这些问题

但我也找到一种方法

在调用的时候使用str(getch())

import getch
a = str(getch())
if a == "b'a'":
    print(a)
    print("成功")
else:
    print("失败")
    print(a)

在这里输入的是 a

这个函数只能在cmd控制台使用

(转载请注明,如有侵权请及时联系ljsdwzljs@163.com避免不必要的纠纷,版权所有©ljs)

知识共享许可协议

Python getchwww.ljsdwz.cn 采用 知识共享 署名-相同方式共享 4.0 国际 许可协议进行许可。

pip加速和使用

在很多时候,我们会选择使用Python大量的第三方库,这些库一般都存在PyPi上。而pypi又在国外,用pip下起来很慢。但是,其实在中国也有pypi的镜像。这篇文章也介绍了。

下面是一些pip在中国的源。

阿里云 http://mirrors.aliyun.com/pypi/simple/

中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

豆瓣(douban) http://pypi.douban.com/simple/

清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/

中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

使用方法:

pip install (模块名如 pygame) -i (加pip源,如:https://pypi.tuna.tsinghua.edu.cn/simple/)

这样用起来就方便多了。(主要是速度快)

我相信你一定看到隐私声明了

(转载请注明,如有侵权请及时联系ljsdwzljs@163.com避免不必要的纠纷,版权所有©ljs)

知识共享许可协议
本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。