如何单击热键并在python中打开特定的URL?

时间:2019-04-24 08:11:30

标签: python pynput

点击按钮序列,例如 shift + a 并打开amazon.com。单击另一个按钮序列,例如 shift + e 并打开asyncio.create_task。 该代码适用于ebay.com,但是当我单击热键 shift + e 时,它没有打开ebay.com。 当您打印要单击的键时,您会意识到该程序正在按 Shift e a 。 我不知道为什么程序会打印我不单击的 a

amazon.com

1 个答案:

答案 0 :(得分:0)

首先,最好在组合后清除current,而不要在密钥释放后删除项目,这样会更好,更简单。第二个all(k in current for k in COMBO)仅检查COMBO中的所有元素是否都位于current中,而不检查方向。例如,如果您按下 a + Shift ,它将变成True,这是错误的。 一种解决方案是使用list代替set,并检查COMBOcurrent是否存在(作为切片)。我用this example检查切片列表的存在。

import time
from pynput import keyboard
COMBINATIONS = [
    [keyboard.Key.shift, keyboard.KeyCode(char='a')],
    [keyboard.Key.shift, keyboard.KeyCode(char='A')],
    [keyboard.Key.shift, keyboard.KeyCode(char='e')],
    [keyboard.Key.shift, keyboard.KeyCode(char='E')]
]
current = []


def execute(url):
    keyboard_ctrl = keyboard.Controller()
    keyboard_ctrl.press(keyboard.Key.ctrl_l)
    keyboard_ctrl.press('l')
    keyboard_ctrl.release(keyboard.Key.ctrl_l)
    keyboard_ctrl.release('l')
    time.sleep(0.2)

    for i in url:
        keyboard_ctrl.press(i)
        keyboard_ctrl.release(i)
    # keyboard_ctrl.type(url)
    time.sleep(0.2)
    keyboard_ctrl.press(keyboard.Key.enter)
    keyboard_ctrl.release(keyboard.Key.enter)


def contains_sublist(lst, sublst):
    n = len(sublst)
    return any((sublst == lst[i:i+n]) for i in range(len(lst)-n+1))


def on_press(key):
    global current
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.append(key)
        print(key)
        if any((contains_sublist(current, COMBO)) for COMBO in COMBINATIONS):
            print("Combination pressed!")
            if current[-1] == keyboard.KeyCode(char='a'):
                execute('https://www.amazon.com/')
            if current[-1] == keyboard.KeyCode(char='e'):
                execute('https://www.ebay.com/')
            current = []


with keyboard.Listener(on_press=on_press) as listener:
    listener.join()