当没有跳过输入的选项时,如何绕过 Python3 中的输入提示?
使用一个库,当我调用某个函数时,我将调用 foo() ,系统会提示我输入这样的内容:
def foo():
if input("Proceed?") == 'yes':
take_action()
我需要传递答案才能继续。
但我希望能够使用默认值循环 foo() 来提供提示。
问题是开发人员没有提供为提示提供默认值的选项。
理想情况下,他们会这样编写 foo()
:
def foo(default_response=None):
if default_response == 'yes':
take_action()
elif input("Proceed?") == 'yes':
take_action()
鉴于他们没有提供默认响应的选项,有没有办法让我循环 foo()
并在不更改源代码的情况下自动提供输入?
Using a library that when I call a certain function that I will call foo()
, I am prompted for input as such:
def foo():
if input("Proceed?") == 'yes':
take_action()
I am required to pass in an answer to continue.
But I would like to be able to loop over foo()
with a default value to feed the prompt.
The problem is the developers did not provide an option to supply a default value for the prompt.
Ideally they would have written foo()
like this:
def foo(default_response=None):
if default_response == 'yes':
take_action()
elif input("Proceed?") == 'yes':
take_action()
Given that they did not supply an option for a default response, is there a way for me to loop over foo()
and provide the input automatically without changing the source code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是monkey patch库以临时替换
输入
功能。例如,如果我有如下所示的模块foo.py
:我可以这样编写
bar.py
:如果运行此代码,您将看到第一次调用 foo.foo()
使用默认输入,并在没有提示的情况下继续。第二次通话
to
foo.foo()
会正常提示。One solution is to monkey patch the library to temporarily replace the
input
function. For example, if I have modulefoo.py
that looks like this:I can write
bar.py
like this:If you run this code, you'll see that the first call to
foo.foo()
uses a default input, and proceeds without prompting. The second call
to
foo.foo()
will prompt normally.