pywinauto wait for window to appear and send key-press

Alex Zel picture Alex Zel · Jul 12, 2015 · Viewed 15.8k times · Source

I'm trying to make a small function that will wait until a certain window appear and then send a key-press (alt+i), i've been trying to do this with pywinauto but with no success. from what i've read in the documantation i can use

pywinauto.application.WindowSpecification.Exists()

but i just can't understand how to specify what i'm looking for, i can use either the window title or the process name, but can't find a good explanation.

Also, is there a batter or easier module to use besides pywinauto? i don't need to do complicated automation, just wait for a window and send some keys.

EDIT

Ok i found a solution, a simple function that loops forever

 def auto_accept(*args):
    while True:
        try:
            app = pywinauto.Application()
            app.window_(title='Untitled - Notepad').SetFocus()
            app.window_(title='Untitled - Notepad').TypeKeys("{1}{2}{3}")
        except (pywinauto.findwindows.WindowNotFoundError, pywinauto.timings.TimeoutError):
            pass

But now i always get a warning like "2015-07-13 12:18:02,887 INFO: Typed text to the Notepad: {1}{2}{3}" and i can't filter them out using the warnings module, is there another way to filter\disable them? it's an issue since when i create an exe using py2exe, after the program is closed it tells me there are errors, but the only errors are the warning i get from sendkeys.

Answer

Vasily Ryabov picture Vasily Ryabov · Jul 13, 2015

You can simply use wait/wait_not methods for WindowSpecification object:

from pywinauto.application import Application
app = Application(backend="win32").start('executable')
app.WindowSpecification.wait('enabled').type_keys('%i') # % - alt, ^ - ctrl

WindowSpecification can be set with more details:

app.window(title='Title', class_name='#32770')

All possible parameters for window() method are the same as for find_elements function (this low-level function is not recommended for direct usage).

For long operation you can set timeout for single wait: wait('enabled', timeout=20) or set timeout for every wait globally: Timings.window_find_timeout = 10


EDIT: call this code after import pywinauto to disable logging:

import logging
logger = logging.getLogger('pywinauto')
logger.level = logging.WARNING # or higher

Logger levels:

Level Numeric value 
CRITICAL 50 
ERROR 40 
WARNING 30 
INFO 20 
DEBUG 10 
NOTSET 0