介绍:该xinput
命令允许我设置鼠标的减速参数,我必须这样做,因为我喜欢小鼠标灵敏度,而 Ubuntu 中的最小值对我来说仍然有点太高。所以我使用:
szczepan@szczepan-550P5C:~$ xinput list
⎡ Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
⎜ ↳ A4TECH USB Device id=10 [slave pointer (2)]
⎜ ↳ A4TECH USB Device id=11 [slave pointer (2)]
⎜ ↳ SynPS/2 Synaptics TouchPad id=14 [slave pointer (2)]
⎣ Virtual core keyboard id=3 [master keyboard (2)]
↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)]
↳ Power Button id=6 [slave keyboard (3)]
↳ Video Bus id=7 [slave keyboard (3)]
↳ Video Bus id=8 [slave keyboard (3)]
↳ Power Button id=9 [slave keyboard (3)]
↳ WebCam SC-13HDL11939N id=12 [slave keyboard (3)]
↳ AT Translated Set 2 keyboard id=13 [slave keyboard (3)]
szczepan@szczepan-550P5C:~$ xinput set-prop 11 "Device Accel Constant Deceleration" 5
... 一切都正常。但是每次我插入设备、关机/睡眠后登录时,我都必须使用这些命令。
我的问题:每次检测到此设备时,是否可以强制 Ubuntu 将设备 A4TECH USB 设备的参数“设备加速恒定减速”设置为 5?如果可以,我该怎么做?提前感谢所有的努力。
答案1
介绍
下面的脚本等待用户定义的设备连接并设置适当的值,不断重复该过程,从而允许用户在会话期间多次连接和断开设备。
它读取文件中的用户定义设置~/.xinputmonrc
,该文件必须在启动脚本之前创建
用法
如图所示-h
选项:
usage: xinput_monitor.py [-h] [-q] -d DEVICE
Script that waits for presence of user device and sets preferences as defined in
~/.xinputmonrc file
optional arguments:
-h, --help show this help message and exit
-q, --quiet Blocks on-screen notifications
-d DEVICE, --device DEVICE
device name
笔记:如描述中所述,该文件读取您的主目录在~/.xinputmonrc
哪里。此类文件的示例(请注意需要多个值的属性的数组用法):~
{
"Device Accel Constant Deceleration":5,
"Evdev Scrolling Distance":[1,1,1]
}
假设我们Logitech USB Receiver
在输出中列出了设备xinput
。可以像这样调用该脚本:
python3 xinput_monitor.py -d "Logitech USB Receiver"
该脚本将发出监控已开始的通知:
一旦设备连接成功,它将发出已检测到设备的通知:
如果一切正常,脚本将默默继续并等待设备断开连接:
该-q
选项允许静音所有通知气泡。
获取脚本
源代码可以在这篇文章中找到,也可以Github 上的 Gist
您可以从这里复制源代码,将其保存为,然后在保存它的目录中xinput_monitor.py
使用终端命令使其可执行。chmod +x xinput_monitor.py
源代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sergiy Kolodyazhnyy
Date: August 2nd, 2016
Written for: https://askubuntu.com/q/806212/295286
Tested on Ubuntu 16.04 LTS
usage: xinput_monitor.py [-h] [-q] -d DEVICE
Script that waits for presence of user device
and sets preferences as defined
in ~/.xinputmonrc file
optional arguments:
-h, --help show this help message and exit
-q, --quiet Blocks on-screen notifications
-d DEVICE, --device DEVICE
device name
"""
from __future__ import print_function
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
import subprocess
import argparse
import time
import json
import os
def send_notif(n,title, text):
try:
if Notify.init(__file__):
# n = Notify.Notification.new("Notify")
n.update(title, text)
n.set_urgency(2)
if not n.show():
raise SyntaxError("sending notification failed!")
else:
raise SyntaxError("can't initialize notification!")
except SyntaxError as error:
print(error)
if error == "sending notification failed!":
Notify.uninit()
else:
Notify.uninit()
def run_cmd(cmdlist):
""" Reusable function for running shell commands"""
try:
stdout = subprocess.check_output(cmdlist)
except subprocess.CalledProcessError as pserror:
return pserror.output.decode().strip()
#sys.exit(1)
else:
if stdout:
return stdout.decode().strip()
def list_ids(mouse_name):
""" Returns list of ids for the same device"""
#while True:
mouse_ids = []
for dev_id in run_cmd(['xinput','list','--id-only']).split('\n'):
if mouse_name in run_cmd(['xinput','list','--name-only',dev_id]):
mouse_ids.append(dev_id)
return mouse_ids
def read_config_file(notif):
""" reads ~/.xinputmonrc file """
rcfile = os.path.join( os.path.expanduser('~'),'.xinputmonrc')
try:
with open(rcfile) as config_file:
config_data = json.load(config_file)
except IOError as error:
send_notif(notif, __file__ , error.__repr__() )
else:
if config_data:
return config_data
def set_props(notif,device):
"""Sets properties per each device is
given by list_ids() function"""
props = read_config_file(notif)
# Thiscan also be set manually as in
# commented-out example below
#props = { 'Device Accel Profile':'-1',
# 'Device Accel Constant Deceleration':'3.5',
# 'Device Accel Velocity Scaling':'1.0' }
if not props:
send_notif(notif,'Reading ~/.xinputmonrc failed',
'Please write proper rc file.')
return None
""" set all property-value pair per each device id
Uncomment the print function if you wish to know
which ids have been altered for double-checking
with xinput list-props"""
for dev_id in list_ids(device):
# print(dev_id)
for prop,value in props.items():
if type(value) is not list:
value = [value]
run_cmd(['xinput','set-prop',dev_id,prop] +
[str(item) for item in value ])
def parse_args():
""" Parse command line arguments"""
arg_parser = argparse.ArgumentParser(
description="""Script that waits for """ +
"""presence of user device """+
"""and sets preferences as """ +
"""defined in ~/.xinputmonrc file""")
arg_parser.add_argument(
'-q','--quiet', action='store_true',
help='Blocks on-screen notifications',
required=False)
arg_parser.add_argument(
'-d','--device',
help='device name',
type=str,
required=True)
return arg_parser.parse_args()
def main():
notif = Notify.Notification.new("Notify")
args = parse_args()
while True:
if not args.quiet:
send_notif(notif, __file__ ,
'Wating for ' + args.device )
while args.device not in run_cmd(['xinput','list','--name-only']):
time.sleep(0.25)
pass
time.sleep(0.25) # let xinput catch up
if not args.quiet:
send_notif(notif, __file__,
args.device + ' connected. Setting values')
# set props here
set_props(notif,args.device)
while args.device in run_cmd(['xinput','list','--name-only']):
time.sleep(0.25)
pass
if not args.quiet:
send_notif( notif , __file__ , args.device +
' disconnected. Resuming monitoring' )
if __name__ == '__main__':
main()
笔记
- 可以启动多个实例来监控多个设备,但不建议这样做,因为多个实例读取相同的配置文件。
- 脚本是
python 3
兼容python 2
的,可以运行。 - 咨询如何在 Unity 中手动编辑/创建新的启动器项?为该脚本创建启动器或桌面快捷方式,以便双击启动它
- 为了将此脚本链接到键盘快捷键以方便访问,请查阅 如何添加键盘快捷键?