自动响应程序输出¶
背景¶
命令行程序通常是为交互式shell设计的,通常表现为等待用户输入或“提示”。精心设计的程序提供了预先清空此类提示的选项,从而实现了一个容易自动化的工作流——但对于其他程序,交互性是不可避免的。
谢天谢地,Invoke的 Runner
类不仅将您的标准输入转发到运行程序(允许您手动响应提示),而且还可以配置为自动响应您的响应。
基本用途¶
这种自动化的机制是 watchers
克沃格 Runner.run
方法(以及其他地方的包装,例如 Context.run
和 invoke.run
,这是 StreamWatcher
-配置为监视模式并相应响应的子类实例。其中最简单的是 Responder
,它只在每次看到模式时回复配置响应; watchers module .
备注
就像所有其他的论点一样 run
还可以通过全局设置默认的监视集 configuration files .
例如,此程序需要对“是/否”提示进行手动响应:
$ excitable-program
When you give the OK, I'm going to do the things. All of them!!
Are you ready? [Y/n] y
OK! I just did all sorts of neat stuff. You're welcome! Bye!
你 能够 调用 run("excitable-program")
,手动查看提示,然后手动将y捣碎。但是如果你提供 Responder
像这样::
@task
def always_ready(c):
responder = Responder(
pattern=r"Are you ready? \[Y/n\] ",
response="y\n",
)
c.run("excitable-program", watchers=[responder])
然后 Runner
通过程序的 stdout
和 stderr
通过 responder
,它监视 "Are you ready? [Y/n] "
自动写入 y
(加) \n
模拟按回车键/回车键 stdin
.
备注
的模式参数 Responder
被视为 regular expression
,需要更多的关注(注意在上面的例子中我们是如何摆脱方括号的),但是也提供了更多的力量。