pythonpyautogui

Pyautogui use size() to get two integers


so I am trying to create a bot in python, and for that cause I would need the size of the screen as two integers (x coordinate and y coordinate). I use pyautogui for that case, but the function size() only returns a string:

Size(width=2560, height=1440)

How would i go about "extracting" these values into integer variables?

edit: I managed to fix my problem, it's some spagetthi code, but I can clean it up later, just in case someone has the same problem:

import pyautogui


screen_size = str(pyautogui.size())
screen_size_x, screen_size_y = screen_size.split(",")
screen_size_x= screen_size_x.replace("Size(width=","")
screen_size_y = screen_size_y.replace("height=","")
screen_size_y = screen_size_y.replace(")","")
screen_size_y = screen_size_y.replace(" ","")
screen_size_x = int(screen_size_x)
screen_size_y = int(screen_size_y)
print(screen_size_x)
print(screen_size_y)

Solution

  • I've found multiple examples online of using pyautogui.size(). In all those examples, that method returns a two-item tuple containing width and height. So it seems that your code could be as simple as:

    screen_size_x, screen_size_y = pyautogui.size()
    print(screen_size_x)
    print(screen_size_y)
    

    This is shown in the first example in the pyautogui docs: https://github.com/asweigart/pyautogui/blob/master/README.md

    If you did need to parse the string you mention, here's a cleaner way to do that:

    import re
    str = "Size(width=2560, height=1440)"
    m = re.search(r"width=(\d+).*height=(\d+)", str)
    screen_size_x, screen_size_y = int(m.group(1)), int(m.group(2))
    print(screen_size_x)
    print(screen_size_y)