【问题标题】:Adding readline to sqlite3将 readline 添加到 sqlite3
【发布时间】:2014-05-31 23:32:45
【问题描述】:

我尝试创建一个脚本,为 sqlite3 命令添加 readline 功能,例如历史记录和移动光标。到目前为止,我想出了这个:

#!/usr/bin/env ruby

require 'pty'
require 'expect'
require 'readline'

PTY.spawn("sqlite3") do |reader, writer, pid|
    reader.expect("sqlite> ")
    writer.puts(Readline.readline("sqlite> ", true))
end

但我不知道如何让它打印他们输入的命令的输出。我将不胜感激这方面的任何帮助。谢谢!

【问题讨论】:

  • 你应该阅读rlwrap——它可能会简化你的生活。
  • 天哪,谢谢!我一定会用这个!

标签: ruby sqlite expect readline


【解决方案1】:

找到this tutorial后,我玩了这个。

require 'pty'
require 'expect'
require 'readline'


PTY.spawn("sqlite3") do |reader, writer, pid|
   cmd = Readline.readline("prompt> ", true);
   reader.expect(/^sqlite\>/) {  |r| writer.printf("%s\n",cmd) }
   puts reader.expect(/^sqlite\>/)[0]
end

简而言之,对于您的示例,您只需要添加以下内容:

 puts reader.expect("sqlite> ")[0]

再玩一下,我添加了一个小循环,询问命令,将它们发送到 sqllite3 并发回结果:

require 'pty'
require 'expect'
require 'readline'


PTY.spawn("sqlite3") do |reader, writer, pid|
   reader.expect(/^sqlite\>/)                   # Read up till the prompt.
   loop {
      cmd = Readline.readline("prompt> ", true);   # Get a command.
      writer.printf("%s\n",cmd)                    # Send it.

      r = reader.expect(/^sqlite\>/)               # Get the result
      r[0].lines.to_a[0..-2].each do |l|           # Turn into an array without last line.
         unless l.match(/^ /)                      # Ignore the indented lines
            puts l                                 # Show the result to user
         end
      end
   end

r[0].lines.to_a[0..-2].join 只是删除最后一行的一些黑魔法。

【讨论】:

  • 你知道我怎样才能让它在输入命令后只给出命令的输出,像这样:Hello World 而不是这样:select "Hello World"; Hello World
  • 更新答案只返回查询结果。
  • 大括号在哪里闭合?
猜你喜欢
  • 2011-07-31
  • 2019-06-29
  • 2019-09-18
  • 2013-11-01
  • 2015-05-07
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多