Julie
Julie

Reputation: 13

Get real-time position of cursor on Mac OS X 10.14 with Python 3.7

I am using Python Idle and want to display the mouse cursor's current position. The code is from Al Sweigart's book (Automate the Boring Stuff with Python) but unfortunately the current position just prints continuously.

I have double-checked the code, and insured that the necessary modules were installed in the terminal (pyobjc-framework-Quartz, pyobjc-core, and pyobjc). I have looked on other forums and tried the solution of running the code in the terminal but could not get it to work.

# mouseNow.py - Displays the mouse cursor's current position.

import pyautogui
print('Press Ctrl-C to quit.')
try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr, end='')
        print('\b' * len(positionStr), end='', flush=True)
except KeyboardInterrupt:
    print('\nDone.')

With the current code, IDLE prints the current position repeatedly. With the correct code, IDLE should only show the current mouse position.

Upvotes: 1

Views: 1337

Answers (1)

user9572013
user9572013

Reputation:

You could erase the file's contents with truncate before printing to it:

import pyautogui
print('Press Ctrl-C to quit.')
try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' +str(y).rjust(4)
        print(positionStr, end='')
        print('\b' * len(positionStr), end='', flush=True)
        with open("somefile.txt", "a") as f:

            f.truncate(0)

            f.write("X: {:>4} Y: {:>4}".format(x, y))
except KeyboardInterrupt:
    print('\nDone.')

Upvotes: 1

Related Questions