如何在python模块/脚本中使用xdotool?

cof*_*ode 5 python ubuntu

例如,如果我想使用类似的东西:

xdotool mousemove 945 132

xdotool点击1

为了将鼠标移动到某个位置并单击.在ubuntu中,我可以直接在终端中输入这些命令以获得所需的效果,但我想将它们放在Python脚本中.提前致谢!

Fre*_*Foo 11

import subprocess

subprocess.call(["xdotool", "mousemove", "945", "132"])
Run Code Online (Sandbox Code Playgroud)

等.请参阅subprocess文档.


Joh*_*631 8

我一直在使用 xdotool 和 sh 和 os.system 一段时间,但决定更新所有内容以使用子进程。这样做我遇到了一些小故障,并在谷歌搜索中发现了 Simon 建议的 libxdo python 模块。Python3 有一个小问题——它使用字节串——但转换很简单,而且它比旧的两步过程运行得更流畅和可靠。

这是一些可能有帮助的小代码(显然哈希爆炸需要匹配您的python路径)。这两个函数包括对 Python 3 的字节串 (ascii) 的转换,因此 .encode() 可以在 Python 2 中省略。

#!/home/john/anaconda3/bin/python3.6
import sys
from xdo import Xdo
from time import sleep

def sendkeys(*keys):
    for k in keys: xdo.send_keysequence_window(0, k.encode())

def type(text):
    xdo.enter_text_window(0, text.encode())

sleep(0.5)
xdo = Xdo()

# this updates a row in a spreadsheet with copies from prior row
# first check that this is the intended spreadsheet
if 'Trades' in xdo.get_window_name(xdo.get_active_window()).decode():
    with open('my_data_file_name', 'r') as f:
        trade = (f.readlines()[-int(sys.argv[1])])[:-1]
        t = [s if s else '0' for s in trade.split('\t')]
        type('\t'.join(t[:7]))
        sendkeys('Tab', 'Up', 'ctrl+c', 'Down', 'ctrl+v', 'Right')
        type(' ' + t[-3])
        sendkeys('Tab')
        type(t[-2])
        sendkeys('Tab')
        type(t[-1])
        sendkeys('Tab', 'Up', 'ctrl+c', 'Down', 'ctrl+v', 'Right')
        type('333')
        sendkeys('Tab')
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 6

从2015年起,您还可以使用以下python软件包:https : //github.com/rshk/python-libxdo

  • 它现在似乎没有维护——我有一个分叉版本 [`python-libxdo-ng`](https://github.com/user202729/python-libxdo-ng),它修复了一些错误。该解决方案比“subprocess”快 100 倍 (2认同)