python - 有没有办法在单个函数内自动向多个 raw_input()/input() 提供多个输入字符串

标签 python python-3.x

下面的代码针对 python 2,但对于 python 3,您可以考虑 input() 来回答。

我有一个“set_pwd()”(无法修改,即第 3 方库的一部分):

def set_pwd():
    x = raw_input("Enter the pwd")
    y = raw_input("Confirm the pwd")

现在,自己实现的函数,它试图以尝试输入密码的方式调用上面提到的 set_pwd() 。我可以在第一个提示时应用密码文本,但无法在后续提示中应用密码文本(用于密码确认)。代码如下:

def enter_pwd():
    import sys
    import StringIO
    f1 = sys.stdin
    f = StringIO.StringIO('My123PWD')
    sys.stdin = f
    set_pwd()  # Call to function
    f.close()
    sys.stdin = f1

我尝试探索 f.next() (对于 StringIO)但有帮助。提前致谢。

最佳答案

您的代码标记为Python3,因此我将给出Python3答案,但您提供的代码是Python2.7。您只需使用换行符即可传递多个输入(即 \n):

from io import StringIO
import sys


def set_pwd():
    x = input("Enter the pwd")
    y = input("Confirm the pwd")
    print()
    print("X:", x) # My123PWD
    print("Y:", y) # confirmed

f = StringIO('My123PWD\nconfirmed')
sys.stdin = f
set_pwd()  # Call to function
f.close()
sys.stdin = sys.__stdin__ # sys remembers stdin so just use this to restore it

关于python - 有没有办法在单个函数内自动向多个 raw_input()/input() 提供多个输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428332/

相关文章:

Python,根据输入字符串的格式和内容运行函数

c++ - 为什么 PyObject_Print 崩溃?

python-3.x - 将 .TIF 转换为 .PDF 得到 PIL : Error reading image

python - 如何改进这个类似尾部的Python代码

python - 如何在pyqtgraph中设置单个PlotItem的背景颜色?

python - 与 return 语句一起使用 'elif' 或连续的 'if' 语句更好吗?

python-3.x - 比较不同形状的 Pandas 数据框

python - Pandas - 将多个值解压到另一列并合并到其中的一个 Df

python - 如何在 pandas 数据框中有一个空的第一行

python - 使用 'in' 运算符的多值检查 (Python)