'Pynput+pyautogui+json - trouble with keyboard/mouse macros code

I have a code that works pretty well except one part -- it does nothing when I press alt_l, but it should move mouse cursor to the coordinates that were saved by pressing crtl_l

Am I doing something wrong?

import pyautogui
from pynput import keyboard
import json


def on_press(key):
    if key == keyboard.Key.ctrl_l:
        print(pyautogui.position())

    with open("cf.json", "w", encoding='utf-8') as f:
        json.dump(list(pyautogui.position()), f, ensure_ascii=False, indent=4)

    if key == keyboard.Key.alt_l:
        with open("cf.json") as f:
            x, y = json.load(f)
        pyautogui.moveTo(x, y)

    if key == keyboard.Key.esc:
        return False


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


Solution 1:[1]

Try to change the part where key is pressed from keyboard.Key to keyboard.is_pressed:

from:

if key == keyboard.Key.alt_l:
    with open("cf.json") as f:
        x, y = json.load(f)
    pyautogui.moveTo(x, y)

to:

if keyboard.is_pressed('alt+l'):
    with open("cf.json") as f:
        x, y = json.load(f)
    pyautogui.moveTo(x, y)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guilherme Matheus