下面的代码针对 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/