Python управление программами windows

What is pywinauto¶

pywinauto is a set of python modules to automate the Microsoft Windows GUI. At its simplest it allows you to send mouse and keyboard actions to windows dialogs and controls.

Installation¶

pywinauto can be installed with pip and conda. Run pip install pywinauto or conda install -c conda-forge pywinauto .

Manual installation¶

  • Install the following Python packages
    • pyWin32
    • comtypes
    • six
    • (optional)Pillow (to make screenshoots)

    To check you have it installed correctly Run Python

    >>> from pywinauto.application import Application >>> app = Application(backend="uia").start("notepad.exe") >>> app.UntitledNotepad.type_keys("%FX") 

    How does it work¶

    The core concept is described in the Getting Started Guide.

    A lot is done through attribute access ( __getattribute__ ) for each class. For example when you get the attribute of an Application or Dialog object it looks for a dialog or control (respectively).

    myapp.Notepad # looks for a Window/Dialog of your app that has a title 'similar' # to "Notepad" myapp.PageSetup.OK # looks first for a dialog with a title like "PageSetup" # then it looks for a control on that dialog with a title # like "OK" 

    This attribute resolution is delayed (with a default timeout) until it succeeds. So for example if you select a menu option and then look for the resulting dialog e.g.

    app.UntitledNotepad.menu_select("File->SaveAs") app.SaveAs.ComboBox5.select("UTF-8") app.SaveAs.edit1.set_text("Example-utf8.txt") app.SaveAs.Save.click() 

    At the 2nd line the SaveAs dialog might not be open by the time this line is executed. So what happens is that we wait until we have a control to resolve before resolving the dialog. At that point if we can’t find a SaveAs dialog with a ComboBox5 control then we wait a very short period of time and try again, this is repeated up to a maximum time (currently 5 seconds!)

    This is to avoid having to use time.sleep or a “wait” function explicitly.

    If your application performs long time operation, new dialog can appear or disappear later. You can wait for its new state like so

    app.Open.Open.click() # opening large file app.Open.wait_not('visible') # make sure "Open" dialog became invisible # wait for up to 30 seconds until data.txt is loaded app.window(title='data.txt - Notepad').wait('ready', timeout=30) 

    Some similar tools for comparison¶

    • Python tools
      • PyAutoGui — a popular cross-platform library (has image-based search, no text-based controls manipulation).
      • Lackey — a pure Python replacement for Sikuli (based on image pattern matching).
      • AXUI — one of the wrappers around MS UI Automation API.
      • winGuiAuto — another module using Win32 API.
      • Other scripting language tools
        • (Perl) Win32::GuiTest
        • (Ruby) Win32-Autogui — a wrapper around Win32 API.
        • (Ruby) RAutomation — there are 3 adapters: Win32 API, UIA, AutoIt.
        • Other free tools
          • (C#) Winium.Desktop — a young but good MS UI Automation based tool.
          • (C#) TestStack.White — another good MS UI Automation based library with a long history.
          • AutoIt — free tool with its own Basic-like language (Win32 API based, no .NET plans)
          • AutoHotKey — native C++ tool with its own scripting language (.ahk)
          • “Awesome test automation” list on GitHub
          • A big list of open source tools for functional testing
          • Commercial tools
            • WinRunner (http://www.mercury.com/us/products/quality-center/functional-testing/winrunner/)
            • SilkTest (http://www.segue.com/products/functional-regressional-testing/silktest.asp)
            • Many Others (http://www.testingfaqs.org/t-gui.html)

            Why write yet another automation tool if there are so many out there?¶

            There are loads of reasons 🙂

            Takes a different approach:

            Most other tools are not object oriented you end up writing stuff like:

            window = findwindow(title = "Untitled - Notepad", "%OF") # Format -> Font fontdialog = findwindow("title = "Font") buttonClick(fontdialog, "OK")

            I was hoping to create something more userfriendly (and pythonic). For example the translation of above would be:

            win = app.UntitledNotepad win.menu_select("Format->Font") app.Font.OK.click() 

            Python makes it easy: Python is a great programming language, but there are no automation tools that were Pythonic (the very few libraries were implemented in Python). Localization as a main requirement:

            “I work in the localization industry and GUI automation is used extensively as often all you need to do is ensure that your UI behaves and is correct with respect to the Source UI. This is actually an easier job then for testing the original source UI.

            But most automation tools are based off of coordinates or text of the controls and these can change in the localized software. So my goal ( though not yet implemented) is to allow scripts to run unchanged between original source language (often English) and the translated software (Japanese, German, etc).”

            © Copyright 2018, Mark Mc Mahon and Contributors Revision aea0429b .

            Versions latest stable 0.6.8 0.6.7 0.6.6 0.6.5 0.6.4 0.6.3 0.6.2 0.6.1 0.6.0 uia atspi Downloads pdf html On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

            Источник

            Управление Windows приложениями с помощью PowerShell через Telegram бота на Python

            Работаю инженером в компании, у которой есть несколько удаленных филиалов и в каждом из них работают сервера видеонаблюдения. Охрана круглосуточно ведет мониторинг происходящего, а приложение видеонаблюдения на этих серверах имеет привычку зависать. Звонки от охраны могут поступать в любое время суток, что очень неудобно, когда ты спишь или нет доступа к ПК, чтобы подключиться удаленно и перезапустить программу

            Я начал задумываться о решении данной проблемы путем создания Telegram бота на Python, с помощью которого можно комфортно перезапускать ПО или делегировать это функцию не компетентным людям, например охране

            При всем многообразии решений с помощью Telegram ботов, информации на эту тему в интернете мало, поэтому решил поделиться ей здесь, возможно кому то пригодиться

            Так же по этому примеру, через запуск скриптов, возможно управлять инфраструктурой серверов предприятия и пр. все зависит от вашей фантазии

            Настройка на серверах

            Для начала нужно выполнить настройки на серверах (управляемых ПК) с помощью PowerShell, запустить оснастку необходимо от имени администратора

            Включить и настроить WinRM на удаленном компьютере:

            Enable-PSremoting -skipnetworkprofilecheck –force
            Set-executionpolicy remotesigned

            На клиентском (управляющем) ПК тоже необходимо выполнить настройки

            • Добавить IP адреса компьютеров, к которым мы будем подключаться в TrustedHosts или же просто разрешить все добавив *
            Set-item wsman:\localhost\client\trustedhosts *

            Теперь с помощью PowerShell ISE создадим скрипт для запуска/перезапуска процесса программы, которую необходимо перезапустить, тут же можно будет проверить его выполнение

            $proc = Get-Process | Where-Object $proc.Kill() Start-Process "C:\apps\Путь к программе "

            Далее на серверах создадим простую задачу без триггеров и расписания в планировщике заданий, где укажем только действие на запуск нашего скрипта

            Перейдем к настройке клиента

            В качестве клиентского компьютера использовалась виртуальная машина с Windows 10

            Сервера видеонаблюдения не входят в домен, поэтому придется обойти авторизацию, для этого нам необходимо создать одинаковых пользователей с правами администратора и одинаковым паролем на серверах и клиентском ПК и все действия ниже нужно выполнять под этим пользователем

            На клиентском ПК создаем скрипты запуска заданий, которые мы создали на серверах

            Invoke-Command -ComputerName 'IP адрес' -ScriptBlock

            Чтобы в дальнейшем наш бот смог выполнять эти скрипты, назначаем программу PowerShell для их выполнения по умолчанию, изначально назначен блокнот

            Создаем Telegram бота

            Находим контакт с именем @BotFather, пишем /newbot, далее указываем название бота

            Отсюда нам понадобится token нашего бота

            Далее при помощи команды /mybots выбираем и редактируем нашего бота, здесь мы можем настроить меню для запуска наших команд

            Устанавливаем Python

            Забегая вперед, скажу, что библиотека Python, которую мы будем подключать, почему то работала с ошибками в некоторых версиях Python, я установил PyCharm, Python 3.9.13 вместе с IDE, с ним все работало корректно. Ссылка https://www.jetbrains.com/pycharm/

            Далее открываем Cmd или PowerShell от имени администратора и устанавливаем библиотеку для управления нашим ботом

            Теперь напишем код нашего Telegram бота

            import telepot, time, subprocess def remote(msg): content_type, chat_type, chat_id = telepot.glance(msg) if (content_type == 'text'): command = msg['text'] print ('Got command: %s' % command) if '/address1' in command: #Комманда в Telegram p = subprocess.Popen(expert1, shell=True) #Указываем переменную p = subprocess.Popen(expert2, shell=True) bot.sendMessage(chat_id, "DONE") #Вывод сообщения в чат if '/address2' in command: p = subprocess.Popen(expert3, shell=True) p = subprocess.Popen(expert4, shell=True) p = subprocess.Popen(expert5, shell=True) bot.sendMessage(chat_id, "DONE") if '/address3' in command: p = subprocess.Popen(expert6, shell=True) p = subprocess.Popen(expert7, shell=True) bot.sendMessage(chat_id, "DONE") bot = telepot.Bot('Ваш token Telegam бота') #Указываем token Telegam бота expert1 = 'C:\Telegram\expert1.ps1' #Указваем путь к скрипту expert2 = 'C:\Telegram\expert2.ps1' expert3 = 'C:\Telegram\expert3.ps1' expert4 = 'C:\Telegram\expert4.ps1' expert5 = 'C:\Telegram\expert5.ps1' expert6 = 'C:\Telegram\expert6.ps1' expert7 = 'C:\Telegram\expert7.ps1' bot.message_loop(remote) while 1: time.sleep(20)

            Источник

            Читайте также:  Javascript span style font size
Оцените статью