在一行中请求多个用户输入

4 投票
3 回答
567 浏览
提问于 2025-04-18 16:39

我正在使用Python 3,想要让程序在一行里问用户输入两个信息。

我想要的输出示例如下:

enter first input:                      enter second input:

不过我知道的询问多个用户输入的方式是这样的:

first_input = input("enter first input: ")
second_input = input("enter second input: ")

#output
enter first input:
enter second input: 

我想要的这种方式可能实现吗?如果可以的话,有人能教我怎么做吗?

3 个回答

0

这可能会对你有帮助

import sys
inputarr=sys.stdin.read().split()
print("input 1:",inputarr[0])
print("input 2:",inputarr[1])

你可以使用其他的分隔符

如果这不是你想要的,记得告诉我哦!

1
choices = raw_input("Please enter two input and seperate with space")
value1, value2 = choices.split(" ")

现在,如果你输入 1 56 这样的内容,那么 value1 就会变成 1,而 value2 就会变成 56。你还可以为 split 函数选择其他的分隔符。

1

这主要取决于你的环境。

下面是一个只适用于Windows的解决方案:

from ctypes import *
from ctypes import wintypes

def get_stderr_handle():
    # stdin handle is -10
    # stdout handle is -11
    # stderr handle is -12
    return windll.kernel32.GetStdHandle(-12)

def get_console_screen_buffer_info():
    csbi_ = CONSOLE_SCREEN_BUFFER_INFO()
    windll.kernel32.GetConsoleScreenBufferInfo(get_stderr_handle(), byref(csbi_))
    return csbi_

class CONSOLE_SCREEN_BUFFER_INFO(Structure):
    """struct in wincon.h."""
    _fields_ = [
    ("dwSize", wintypes._COORD),
    ("dwCursorPosition", wintypes._COORD),
    ("wAttributes", wintypes.WORD),
    ("srWindow", wintypes.SMALL_RECT),
    ("dwMaximumWindowSize", wintypes._COORD),
]

csbi = get_console_screen_buffer_info()
first_input = input("enter first input: ")
cursor_pos = csbi.dwCursorPosition
cursor_pos.X = len("enter first input: ") + len(first_input) + 1
windll.kernel32.SetConsoleCursorPosition(get_stderr_handle(), cursor_pos)
second_input = input("enter second input: ")

下面是一个Linux的解决方案,它使用了退格符。如果你使用的是较旧的Python版本,这里有一些get_terminal_size()的实现方式在这里

from shutil import get_terminal_size
first_input = input("enter first input: ")
second_input = input("\b"*(get_terminal_size()[0] - len("enter first input: ") - len(first_input) - 1) + "enter second input: ")

撰写回答