Search code examples
python-3.xwindowspyautogui

PyAutoGUI not writing expected Output with python code


I have the problem that pyautogui doesn't write what I programmed into it. When I try to use go_to it writes it incorrectly. I have written this code:

import pyautogui as pag 
import time

def open_chat():
    pag.write("t")

def close_chat():
    pag.press("esc")

def go_to(x, y, z):
    pag.write(" #goto", x, y, z)

print("start")

time.sleep(20)
open_chat()
go_to(x= 1,y= 1, z= 1)


print("ende")

I expected that the code gives me this output:

t #goto 1 1 1

but I got this output:

t 'goto

I have tried to change the code a few times but the result was the same.


Solution

  • Pyautogui's write (which is an alias for typewrite) functions differently than Python's built-in print function. If you look at the function signatures you'll see how print accepts an arbitrary number of objects to print, and typewrite accepts a single message to type. The * before objects in the signature indicates that it will accept 0 or more positional arguments, and that a tuple of all arguments passed will be assigned to the variable objects in the function's body.

    print(*objects, sep=' ', end='\n', file=None, flush=False)
    typewrite(message, interval=0.0, logScreenshot=None, _pause=True)
    

    When you call pag.write(" #goto", x, y, z) only the first object is typed. Best practice would be to generate a string containing the entirety of what you want typed into the field, and pass that single string to typewrite. String concatenation works, as does string interpolation, but f-strings, or str.format are recommended.