在单行中询问多个用户输入

4

我正在使用 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: 

我正在寻找的方案可行吗?如果可以,有人能教我如何做吗?

请要求用户输入两个以空格分隔的数字,然后按回车键。然后使用Split()函数进行分割 :) - vks
3
这是可能的,但需要更多努力,如果你是初学者,这并不容易。你确定要做这个吗? - Burhan Khalid
嗯...我想我会试一试...你能在代码之间解释并展示给我吗? - user3921890
3个回答

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

现在,如果你输入1 56或类似的内容,value1将是1,而value2将是56。你可以选择其他分隔符来使用split函数。

这并不完全符合提问者的要求。 - simonzack
这是我知道的另一种方式。让他决定吧。 - fatiherdem
好的,这对我的朋友有帮助,谢谢...不过,我正在寻找另一个。 - user3921890

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: ")

对我来说不起作用...输出是一系列的方框,当我在它们之间点击时会移动。 - user3921890
你使用的终端是什么,以及使用的操作系统是哪个? - simonzack
你所说的终端是指个人电脑吗?我使用的是安装了Windows 7操作系统的华硕笔记本电脑。我有一个问题关于你的回答,我正在寻找的答案是否真的那么依赖于我的终端环境;或者这只是我将遇到的少数几个答案之一? - user3921890
尝试仅适用于Windows的解决方案,已在Windows 7上测试。 - simonzack
输出对我来说没有改变;我认为我缺少某些东西。 - user3921890
让我们在聊天中继续这个讨论。点击此处进入聊天室 - user3921890

0

这可能会有所帮助

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

你可以使用任何其他分隔符

如果这不是你要找的,请通知我!


它的easy sys包括系统特定的参数和函数,stdin是解释器标准输入流的文件对象。sys.stdin.read()将从标准输入读取直到达到EOF,而sts.stdin将一次读取一行。 - Namit Sinha
嗯...好的...但是,我没有理解inputarr[]部分。 - user3921890
抱歉,我搞砸了:P 应该是sys.stdin.read().split()。"sys.stdin.read()"会读取输入文件直到达到EOF,而没有任何参数的split()类似于split(" "),即它将删除所有空格并将元素放入列表中。 - Namit Sinha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接