首页 > 解决方案 > Ruby - 在 Windows 环境中调用命令并与 shell 交互

问题描述

我正在命令行中从 Ruby 脚本中运行一个 .exe 文件,该脚本询问用户是/否响应。我想知道用户如何在 Windows 环境中与之交互。

我已经尝试了所有可能的选项:system、反引号、、%x()Open3、Open4 ......但它们都不起作用。

一些帖子([1][2])使用 PTY 解决了该问题,但据我所知,Windows 中没有 PTY 模块的实现。还有什么想法吗?

标签: rubywindowsshellcommand-lineinterop

解决方案


似乎这也在 Windows 下工作

pipe = IO.popen('your.exe', 'w+', :err => [:child, :out])
@pipe.each_line do |line|
  if /pattern matching question/ =~ line
    break
  end
end
pipe.puts('Yes')
# another test can be here
pipe.close

明智地使用https://ruby-doc.com/stdlib/libdoc/timeout/rdoc/Timeout.html


推荐阅读