如果我理解正确,那么您想要做的就是获取输入而不回显换行符。如果您使用的是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.")


