https://raw.githubusercontent.com/beuaaa/pywinauto_recorder/master/Images/logo.png?sanitize=true

Description

“Pywinauto recorder” records user interface actions and saves them in a Python script. The saved Python script can be run to replay the user interface actions previously recorded.

“Pywinauto recorder” is a unique inspect/record/replay tool in the open source field because it generates reliable scripts without hard-coded coordinates thanks to Pywinauto.

Pywinauto is a library that uses accessibility technologies allowing you to automate almost any type of GUI: MFC, VB6, VCL, simple WinForms controls and most of the old legacy apps, WinForms, WPF, Store apps, Qt, and browsers.

The functions of the generated Python script return Pywinauto wrappers so it can be enhanced with Pywinauto methods.

Pywinauto_recorder for Windows

  • “pywinauto_recorder.exe” is a standalone application, it’s the compiled version of “pywinauto_recorder.py” for 64-bit Windows.

Download installer
  • “pywinauto_recorder.py” is the main source, you will find the Python code downloading the github clone.

Download GitHub clone

Usage

  • Double click on “pywinauto_recorder.exe” or run “python.exe pywinauto_recorder.py” to start the recorder.

  • The recorder is started in display information mode, a tray icon is added in the right-side of the Windows Taskbar.

  • Press CTRL+SHIFT+f to copy the code that finds the element colored green or orange to the clipboard.

  • Press CTRL+ALT+r to switch to “Record” mode.

  • If the element below the mouse cursor can be uniquely identified, it will turn green or orange.

  • You can then click or perform another action on the user interface and it will be recorded in the generated Python script.

  • Repeat this process performing a few actions on the user interface and when you’re done press CTRL+ALT+r to end recording.

  • The generated Python script is saved in the “Pywinauto recorder” folder in your home folder and copied in the clipboard.

  • Click on “Quit” in the tray menu.

  • To replay a Python script, you can drag and drop it to “pywinauto_recorder.exe”

Icons

Some transparent icons are displayed at the top left of the screen:
  • an icon corresponds to Record/Stop mode. Press CTRL+ALT+r to switch.

  • a magnifying glass icon corresponds to Display information mode.

  • a bulb icon corresponds to Smart mode. Press CTRL+ALT+S to activate it.

  • another icon displays a green bar at each iteration of the loop. It allows you to see how fast the loop is running.

More explanations

The main of “Pywinauto recorder” is an infinite loop where at each iteration it:
  1. finds the path of the element under the mouse cursor. The path is formed by the window_text and control_type pair of the element and all its ancestors.

  2. searches for an unambiguous path, if found, it colors the element region green or orange.

  3. records a user action in a file involving the last recognized unique path.

Note

To reflect the position of the mouse cursor as closely as possible, an offset is added to the user actions recorded in the generated Python script. This offset is proportional to the size of the element and relative to the center of the element.

If the path of the element under the mouse cursor is not ambiguous, the region of the element is colored green. Otherwise two strategies are used to try to disambiguate the path in the following order:
  1. All elements having the same path are ordered in a 2D array. The path of the element region under the mouse cursor is disambiguated by adding a row index and a column index so that it is colored orange. The other element regions are colored red

  2. When Smart mode is enabled, an element whose path is unambiguous is searched on the same line on the left, if found its region is colored blue and the element under the mouse cursor is colored orange.

Pywinauto recorder tests

The tests are good examples of how to use the player API. The tests are grouped by application:

Pywinauto recorder API

Setup

If you want to replay the actions of a script generated by “pywinauto_recorder.exe” in your Python interpreter you must install the pywinauto_recorder package:

pip install -U pywinauto_recorder

API documentation

The following table lists the useful methods and classes for the ‘Player’ and ‘Recorder’ modules:

pywinauto_recorder.player

This module contains functions to replay a sequence of user actions automatically.

pywinauto_recorder.recorder

This module contains functions and classes allowing to record a sequence of user actions.

Element paths and UIPath

The functions of the player that act on an element, like find(), click() or move(), identify it with a path: the names and the control types of the element and of its ancestors, from its window. The recorder writes these paths in the scripts. This page explains all the ways to identify an element with a path: to read a recorded script, to make it more robust, or to write a script.

The path of an element

A path is a list of entries joined by ->. An entry gives the name and the control type of an element, separated by ||:

click("Calculator||Window->*->Number pad||Group->One||Button")
  • The first entry is the window of the element: here the window named “Calculator”, whose control type is “Window”.

  • The last entry is the element: here the button named “One”.

  • The entries between them are the ancestors of the element. Here * replaces some of them (see below).

The names and the control types are the ones of UI Automation, the accessibility technology used by Pywinauto: Button, Edit, Text, Window, Pane, Group, List, ListItem, MenuItem, and so on. They are compared exactly, with the case and the spaces:

  • an entry without name, like ||Pane, designates an element whose name is empty;

  • an entry without ||, like One, designates an element that has this name, whatever its control type.

To see the path of an element, move the mouse cursor over it while Pywinauto recorder is in display information mode: the tooltip displays its path. CTRL+SHIFT+f copies the code that finds this element to the clipboard. In a script, a path is a Python string: the recorder writes the special characters of the names with a backslash, like \" for a quote or \t for a tab.

UIPath blocks

A UIPath block gives the beginning of the paths used inside it: these paths are relative to the path of the block. The blocks can be nested. The recorder writes the window, and the part of the paths that the next actions have in common, in UIPath blocks:

from pywinauto_recorder.player import UIPath, click, find

with UIPath("Calculator||Window"):
    with UIPath("*->Number pad||Group"):
        click("One||Button")  # Calculator||Window->*->Number pad||Group->One||Button
        click("Two||Button")
    find().set_focus()  # the element of the block: the window "Calculator"
  • Without path, or with an empty path, a function designates the element of the block: here find() returns the window.

  • A path that ends with ~Absolute_UIPath is a full path: the path of the blocks is not added to it. It designates an element of another window inside a block, for example the destination of a drag and drop: drag_and_drop("One||Button", "Other window||Window->*->Destination||List~Absolute_UIPath").

  • UIPath(path, absolute_path=True) starts a block whose path replaces the path of the blocks around it.

Several elements with the same path

find(), and the functions that use it, need one element. When several elements match a path, the search is done again until the timeout, because the user interface may be changing, and then a FailedSearch exception lists the elements found. find_all() returns all the elements that match a path, and exists() returns None instead of raising an exception when no element is found.

To designate one element among several, add ancestors to the path, use a regular expression, or use the [] operator.

Wildcards and regular expressions

* is an entry that replaces any number of entries, zero included:

  • Calculator||Window->*->One||Button designates the button “One” anywhere in the window “Calculator”;

  • *->One||Button: as the first entry, * designates any window;

  • Calculator||Window->* designates all the elements of the window, for find_all().

An entry that begins with RegEx: and a space has a name that is a regular expression (see the module re of Python):

  • the regular expression must match the beginning of the name: RegEx: Display is||Text designates the text “Display is 3”. Add $ to match the whole name: RegEx: .* - Notepad$||Window;

  • the control type is still compared exactly: RegEx: .*||Button designates any button;

  • the special characters of regular expressions are escaped with a backslash, which is doubled in a Python string, unless the string is a raw string: r"RegEx: .* - Notepad\+\+$||Window".

A name that changes, like the title of a window that contains the name of a file, is a typical use of a regular expression.

The [] operator

When several elements match a path, the recorder adds the [] operator at the end of the path, to designate one of them. It has 2 forms:

with UIPath("Calculator||Window->*->Number pad||Group"):
    click("RegEx: .*||Button#[0,1]")              # row 0, column 1: "Eight"
    click("RegEx: .*||Button#[Seven||Button,1]")  # column 1, row of "Seven": "Eight"

#[row,column]: the elements that match the path are sorted in rows, from the top, and in columns, from the left. Here, the first row of the number pad is “Seven”, “Eight”, “Nine”. The elements smaller than 8 pixels, and the elements that are not visible, are not sorted. An element is in the row of the first element of the row when their tops differ by less than 20 pixels, or by less than their height when all the elements have the same height. The indices change when the elements move, for example when the window is resized: a reference element is more robust.

#[path of a reference element,column]: the element is in the row of a reference element, at the given column. The path of the reference element must designate one element only: it is relative to the UIPath blocks too, unless it ends with ~Absolute_UIPath. The recorder writes this form in Smart mode: in a table, the reference element is often a cell whose text identifies the row.

The [] operator is always at the end of a path. When only one element matches the path, this element is returned, and the indices are not checked.

While Pywinauto recorder displays information or records, the element under the mouse cursor is colored green when its path is unique. Otherwise, the element designated with the [] operator is colored orange, the other elements that match the path are colored red, and the reference element is colored blue (see Pywinauto_recorder for Windows).

The position in the element

%(dx,dy) at the end of a path gives the position of the mouse cursor in the element, for move(), click() and the other functions that move the mouse. dx and dy are percentages of the half width and of the half height of the element, from its center: %(0,0) is the center, %(-100,-100) the top left corner, and %(100,0) the middle of the right side. The recorder writes them when the option “% relative coordinates” of its menu is checked, to click where the user clicked: click("Address and search bar||Edit%(-87.50,-20.00)"). find() ignores them. In an absolute path, %(dx,dy) is before ~Absolute_UIPath.

Other ways to identify an element

  • A Pywinauto wrapper, returned by find() for example, can replace a path: click(wrapper).

  • Coordinates of the screen, in pixels, can replace a path in the functions that move the mouse: move((66, 66)) or click((66, 66)).

  • menu_click() has its own path, made of the names of the menu items: menu_click("File->New").

  • focus_on_application() restricts the search to the window of an application.

  • A path dictionary gives names to the paths, so that the scripts do not repeat them (see Path dictionary).

Path dictionary

A path dictionary gives names, the keys, to the paths of the elements. A script uses the keys instead of the paths: the paths are written once, in the dictionary. When the application changes, only the dictionary is changed, not the scripts. For example, with the same key file and another definition file, the same scripts automate another version of the application, or the application in another language.

The dictionary files

A path dictionary is made of 2 text files that have the same lines:

  • the key file (.key) gives the key of an element on each line;

  • the definition file (.def) gives, on the same line, the definition of this element: its path relative to its parent, written like in a script (see Element paths and UIPath).

The tabs at the beginning of the lines of the definition file give the hierarchy of the elements: the parent of an element is on the last line above it that has one tab less. The key file is indented the same way, so that the 2 files can be compared line by line, but its indentation is ignored.

For example, Calculator.key and Calculator.def describe the number pad and the operators of the Calculator of Windows:

Calculator.key

Calculator.def

Calculator
    Number pad
        0
        1
        2
        3
        4
        5
        6
        7
        8
        9
    Standard operators
        /
        *
        -
        +
        =
Calculator||Window->*
    Number pad||Group
        Zero||Button
        One||Button
        Two||Button
        Three||Button
        Four||Button
        Five||Button
        Six||Button
        Seven||Button
        Eight||Button
        Nine||Button
    Standard operators||Group
        Divide by||Button
        Multiply by||Button
        Minus||Button
        Plus||Button
        Equals||Button

Note

The indentation of the definition file must be made of tab characters, one tab per level. This page displays the tabs as spaces: to start from files that have the tabs, download Calculator.key and Calculator.def.

Using a dictionary in a script

load_dictionary() loads the 2 files. Then shortcut() returns the definition of a key, to use in nested UIPath blocks that follow the hierarchy of the dictionary:

from pywinauto_recorder.player import load_dictionary, shortcut, UIPath, click

load_dictionary("Calculator.key", "Calculator.def")
with UIPath(shortcut("Calculator")):
    with UIPath(shortcut("Number pad")):
        click(shortcut("1"))
    with UIPath(shortcut("Standard operators")):
        click(shortcut("+"))
    with UIPath(shortcut("Number pad")):
        click(shortcut("2"))
    with UIPath(shortcut("Standard operators")):
        click(shortcut("="))

Here shortcut("1") returns "One||Button", so the first click is on the element "Calculator||Window->*->Number pad||Group->One||Button".

full_definition() returns the full path of a key: the definitions of its parents and its definition, joined by ->. It does not need UIPath blocks:

from pywinauto_recorder.player import load_dictionary, full_definition, click

load_dictionary("Calculator.key", "Calculator.def")
click(full_definition("1"))  # Calculator||Window->*->Number pad||Group->One||Button
click(full_definition("+"))
click(full_definition("2"))
click(full_definition("="))

Writing a dictionary

The definitions are the entries of the paths written by the recorder, for example in a recorded script, or in the code that CTRL+SHIFT+f copies for the element under the mouse cursor: each entry, or group of entries joined by ->, goes on its own line, indented under the line of its parent.

The files follow these rules:

  • The 2 files have the same number of lines: line n of the key file is the key of line n of the definition file. The empty lines are ignored, but a line must be empty in both files.

  • The indentation of the definition file is made of tabs, one tab per level, and a line is at most one level deeper than the line above it. The spaces and the tabs at the end of the lines are ignored.

  • A definition is written like a path in a script, but without the quotes, and without the backslash before \ and ". It can use regular expressions, like RegEx: .* - Notepad||Window, and *. The [] operator, like #[0,1], must be at the end of a path: only the definition of an element without children can use it.

  • A key or a definition cannot contain a tab, because the tabs separate the levels. For an element whose name contains a tab, use a regular expression, for example RegEx: Stop recording.*||MenuItem.

  • The files are read with the UTF-8 encoding, with or without a byte order mark. The parameter encoding of load_dictionary() gives another encoding, for example "cp1252".

  • The names of the files are relative to the current folder. When Pywinauto recorder replays a script file, the current folder is the folder of the script.

load_dictionary() raises a ValueError when the files do not follow these rules: its message gives the file and the line.

Several dictionaries can be loaded: their keys are added to the same dictionary, and a key that is loaded again gets its new definition. shortcut() and full_definition() raise a KeyError for an unknown key.

Contributing to Pywinauto recorder

You are here to help on Pywinauto recorder? Awesome, feel welcome and read the following sections in order to know how to ask questions and how to work on something.

All members of our community are expected to follow our Code of Conduct. Please make sure you are welcoming and friendly in all of our spaces.

Get in touch

  • Ask usage questions (“How do I?”) on StackOverflow.

  • Report bugs, suggest features or view the source code on GitHub.

Contributing to development

If you want to deep dive and help out with development on Pywinauto recorder, then first get the project installed locally. After that is done we suggest you have a look at tickets in our issue tracker that are labelled Good First Issue. These are meant to be a great way to get a smooth start and won’t put you in front of the most complex parts of the system.

If you are up to more challenging tasks with a bigger scope, then there are a set of tickets with a Enhancement tag. These tickets have a general overview and description of the work required to finish. If you want to start somewhere, this would be a good place to start.

When contributing code, then please follow the standard Contribution Guidelines set forth at contribution-guide.org.

Contributing to documentation

Documentation for Pywinauto recorder itself is hosted at https://pywinauto-recorder.readthedocs.io.

At https://docs.readthedocs.io there are guidelines around writing and formatting documentation for the project.

Code of Conduct

Like the technical community as a whole, the Pywinauto recorder team and community is made up of a mixture of professionals and volunteers from all over the world, working on every aspect of the mission - including mentorship, teaching, and connecting people.

Diversity is one of our huge strengths, but it can also lead to communication issues and unhappiness. To that end, we have a few ground rules that we ask people to adhere to. This code applies equally to founders, mentors and those seeking help and guidance.

This isn’t an exhaustive list of things that you can’t do. Rather, take it in the spirit in which it’s intended - a guide to make it easier to enrich all of us and the technical communities in which we participate.

This code of conduct applies to all spaces managed by the Pywinauto recorder project. This includes IRC, the mailing lists, the issue tracker, and any other forums created by the project team which the community uses for communication. In addition, violations of this code outside these spaces may affect a person’s ability to participate within them.

  • Be friendly and patient.

  • Be welcoming. We strive to be a community that welcomes and supports people of all backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability.

  • Be considerate. Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we’re a world-wide community, so you might not be communicating in someone else’s primary language.

  • Be respectful. Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a productive one. Members of the Pywinauto recorder community should be respectful when dealing with other members as well as with people outside the Pywinauto recorder community.

  • Be careful in the words that you choose. We are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren’t acceptable. This includes, but is not limited to:

    • Violent threats or language directed against another person.

    • Discriminatory jokes and language.

    • Posting sexually explicit or violent material.

    • Posting (or threatening to post) other people’s personally identifying information (“doxing”).

    • Personal insults, especially those using racist or sexist terms.

    • Unwelcome sexual attention.

    • Advocating for, or encouraging, any of the above behavior.

    • Repeated harassment of others. In general, if someone asks you to stop, then stop.

  • When we disagree, try to understand why. Disagreements, both social and technical, happen all the time and Pywinauto recorder is no exception. It is important that we resolve disagreements and differing views constructively. Remember that we’re different. The strength of Pywinauto recorder comes from its varied community, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds a viewpoint doesn’t mean that they’re wrong. Don’t forget that it is human to err and blaming each other doesn’t get us anywhere. Instead, focus on helping to resolve issues and learning from mistakes.

Original text courtesy of the Speak Up! project. This version was adopted from the Django Code of Conduct.