如何解决Python get/pipe/redirect 输入输入到标准输入
我需要编写一个将另一个函数作为参数的函数。参数函数是一个黑匣子,我无法控制它。它调用 input
函数的次数未指定。我想在我的函数中调用参数函数,然后以某种方式获取所有用户输入(可能作为多行字符串?),然后在我的函数中返回它。有没有什么办法可以记录运行参数函数后输入到stdin中的所有字符串?
def func():
input("What is your name? ")
input("How old are you? ")
input("What's your favourite animal? ")
def capture_input(func_to_run):
func_to_run()
return ... # somehow return all the previous writes to stdin here
在 shell 中运行的示例
>>> capture_input(func)
What is your name? Mike
How old are you? 100
What's your favourite animal? Dog
"Mike\n100\nDog" # <- This is what the function should return
解决方法
如果我按照你想要做的正确。将输入存储在一个变量中,然后将它们作为元组返回。然后在 capture_input 中返回您的函数。
def func():
name = input("What is your name? ")
age = input("How old are you? ")
animal = input("What's your favourite animal? ")
return name,age,animal
def capture_input(func_to_run):
return func_to_run()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。