You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中无需xdotool向终端并发发送Tab按键的最简实现方式

解决方案

方案1:Ruby标准库实现(无任何外部依赖)

你当前用xdotool是在X11窗口层面模拟按键,实际上你只需要往当前TTY终端的输入流写入对应控制字符就能触发补全,用Ruby自带的标准库即可实现,不需要安装任何额外程序或gem,无GUI的服务器环境也能正常运行。
示例代码如下:

require "highline"
require "io/console"

# 获取当前终端的设备路径
current_tty = `tty`.chomp

Thread.new do
  sleep 0.1
  # 直接向当前TTY写入控制字符
  File.open(current_tty, 'r+') do |tty|
    tty.write "\t" # 等价于按下Tab键
    tty.write "\b" # 等价于按下BackSpace键
  end
end

HighLine.new.ask("") { |q| q.completion = ["preset text"]; q.readline = true }

方案2:第三方gem实现系统级按键模拟

如果你需要更通用的系统全局按键模拟能力(不限于当前终端),可以使用ruby-uinput gem直接操作Linux内核的uinput子系统实现虚拟键盘输入,不需要依赖xdotool:

  • 安装依赖:gem install ruby-uinput
  • 示例代码:
require "highline"
require "uinput"

Thread.new do
  sleep 0.1
  # 初始化虚拟键盘设备
  Uinput.setup do |dev|
    dev.name = "Ruby Virtual Input"
    dev.enable_key :key_tab
    dev.enable_key :key_backspace
    dev.create_device
  end

  # 发送按键事件
  Uinput.send_key :key_tab
  Uinput.send_key :key_backspace

  Uinput.destroy_device
end

HighLine.new.ask("") { |q| q.completion = ["preset text"]; q.readline = true }

注意:该方案需要当前用户拥有/dev/uinput的读写权限,可通过配置udev规则赋予普通用户对应权限。

内容的提问来源于stack exchange,提问作者Marcus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:27:04