Search code examples
pywinauto

PyWinAuto - Send Key with Python Variables?


I am trying to send text / strings with PyAutoWin in conjunction with variables.

For starters, this works normally. Within Notepad, I am typing "hi chris" on the first line and then "bye" on the second line.

app = application.Application(backend="uia").start("Notepad.exe")
writer_app = app.UntitledNotepad.child_window(title="Text Editor", auto_id="15", control_type="Edit").wrapper_object()
writer_app.type_keys("hi chris\
                     {ENTER}\
                     bye")

But now, let's say I want it to type a variable. The issue here is that PyWinAuto uses {} to distinguish its special keys like ENTER or modifiers like SHIFT, just like how Python f-strings are used.

Below, I have an attempted and failed approach to include a variable in my Notepad.

name = "chris"
app = application.Application(backend="uia").start("Notepad.exe")
writer_app = app.UntitledNotepad.child_window(title="Text Editor", auto_id="15", control_type="Edit").wrapper_object()
writer_app.type_keys(f"hi {name}\
                     {ENTER}\
                     bye")

How do I get both variables and key commands within the type_keys method? Do I just need to have two separate calls?


Solution

  • You were close to what you want. send_keys() function accepts the parameter as string. And you can keep the spaces as well with the additional boolean argument with_spaces You last line should look like below one =

    writer_app.type_keys("hi " + name +\
                         "{ENTER}"
                         "bye", with_spaces=True)