栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:一行中的“打印”和“输入”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:一行中的“打印”和“输入”

如果我理解正确,那么您想要做的就是获取输入而不回显换行符。如果您使用的是Windows,则可以使用msvcrt模块的getwch方法获取单个字符进行输入,而无需打印任何内容(包括换行符),如果不是换行符,则打印该字符。否则,您将需要定义一个getch函数:

import systry:    from msvcrt import getwch as getchexcept importError:    def getch():        """Stolen from http://pre.activestate.com/recipes/134892/"""        import 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 chdef input_():    """Print and return input without echoing newline."""    response = ""    while True:        c = getch()        if c == "b" and len(response) > 0: # Backspaces don't delete already printed text with getch() # "b" is returned by getch() when Backspace key is pressed response = response[:-1] sys.stdout.write("b b")        elif c not in ["r", "b"]: # Likewise "r" is returned by the Enter key response += c sys.stdout.write(c)        elif c == "r": break        sys.stdout.flush()    return responsedef print_(*args, sep=" ", end="n"):    """Print stuff on the same line."""    for arg in args:        if arg == inp: input_()        else: sys.stdout.write(arg)        sys.stdout.write(sep)        sys.stdout.flush()    sys.stdout.write(end)    sys.stdout.flush()inp = None  # Sentinel to check for whether arg is a string or a request for inputprint_("I have", inp, "apples and", inp, "pears.")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419889.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号