people of Stackoverflow! I've just started my coding journey and this seems like the problem that makes me want to give it all up already xD I'm sorry if this is something easy but I really tried out everything I possibly could
I am trying to write a macro that will remember the position of the cursor on the screen with the ctrl key, and return the cursor to that position with the alt key.
import pyautogui
from pynput import keyboard
from contextlib import redirect_stdout
def on_press(key):
if key == keyboard.Key.ctrl_l:
print(pyautogui.position())
with open("cf.py", "a") as f:
with redirect_stdout(f):
print((pyautogui.position()))
everything works pretty well untill I try to get the output results from the cf.py to the main file so I can use them in the alt macro.
from cf import Point
if key == keyboard.Key.alt_l:
print(pyautogui.moveTo(Point(x, y)))
if key == keyboard.Key.esc:
return False
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
That's not a great way of doing things. You should be reading the position from a file, rather than importing the file. There are multiple ways of doing this, but this will probably be the easiest:
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") as f:
json.dump(list(pyautogui.position()), f)
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()