我尝试创建一个脚本,为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
但我不知道如何让它打印出他们输入的命令的输出。我将不胜感激任何帮助。谢谢!
答案 0 :(得分:0)
在找到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
只是删除最后一行的黑魔法。