This question already has answers here:
Possible to get user input without inserting a new line?

(8 个回答)


4年前关闭。




如果我想在 python 中的文本之间输入一些输入,在用户输入内容并按下 Enter 后,我怎么能不切换到新行呢?

例如。:
print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."

应该修改为在一行中输出到控制台说:
I have h apples and h1 pears.

它应该在一条线上这一事实没有更深层次的目的,它是假设性的,我希望它看起来如此。

最佳答案

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

import sys
try:
    from msvcrt import getwch as getch
except ImportError:
    def getch():
        """Stolen from http://code.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 ch


def 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 response


def 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 input
print_("I have", inp, "apples and", inp, "pears.")

关于Python: "Print"和 "Input"在一行中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30142107/

10-12 20:35