连接 USB 键盘时如何更改键盘布局

连接 USB 键盘时如何更改键盘布局

我已经正确配置了两种键盘布局,一种用于内置键盘(英语),一种用于外部 USB 键盘(西班牙语),因此我必须在它们之间手动切换。

在此处输入图片描述

有没有办法配置 Ubuntu,以便当我连接外部 USB 键盘时它会自动更改为西班牙语布局?(断开连接时它会恢复为英语)

答案1

这些是当你连接外部 USB 键盘时让 Linux 在键盘布局之间切换的步骤

  1. 创建一个名为的脚本switchKeyboard.sh,用于在现有的两种布局之间切换
#!/bin/bash
# Get current index of keyboard layout
curKB=$(gsettings get org.gnome.desktop.input-sources current)
isExternalKBconnected=$(lsusb | grep Keyboard | wc -l)
newKB=-1
#If you have more keyboard layouts or in different order or their names are different you need to change this logic

if [[ "$curKB" = "uint32 1" && $isExternalKBconnected -eq 1 ]]; then 
  newKB=0
  newLY='latam'
fi 
if [[ "$curKB" = "uint32 0" && $isExternalKBconnected -eq 0 ]]; then 
  newKB=1
  newLY='us'
fi  
echo -----------------------
date
if [[ newKB -ne -1 && "uint32 ${newKB}" != $curKB ]]; then
    # Change Gnome keyboard layout
    gsettings set org.gnome.desktop.input-sources current $newKB

    echo loadkeys $newLY
    echo setxkbmap $newLY

    # Change the console and X keyboard layout
    sudo loadkeys $newLY
    sudo setxkbmap $newLY
else 
    echo current keyboard layout is kept
fi

# Show the current keyboard layouts and current keyboard index
gsettings get org.gnome.desktop.input-sources sources
gsettings get org.gnome.desktop.input-sources current

注意运行上述脚本不会反映在顶部的可视键盘指示器中,但是如果你在任何控制台或应用程序上打字,你都会注意到变化,而且还有改进的空间,使其更加通用和易读

  1. 使用 python 和 pyudev 监控 usb 设备的连接/断开连接,每次“键盘”usb 设备在连接/断开连接之间切换时,调用第一步的脚本,调用此脚本keyboardDisConnected.py
#!/usr/bin/env python3

import pyudev
import subprocess

def main():
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')
    monitor.start()
    
    for device in iter(monitor.poll, None):

        dt = device.get('DEVTYPE')
        
        if (dt == 'usb_device'):
          # change this path to your home, using ~ does not work
          subprocess.call(['/home/mgg/switchKeyboard.sh'])  

if __name__ == '__main__':
    main()
  1. 运行python keyboardDisConnected.py,连接并断开你的 USB 键盘,你应该看到类似这样的内容:

在此处输入图片描述

  1. 可选择在系统启动时立即运行 python 命令

参考:

相关内容