Эмуляция ввода с клавиатуры python

Keyboard Control Functions¶

The primary keyboard function is write() . This function will type the characters in the string that is passed. To add a delay interval in between pressing each character key, pass an int or float for the interval keyword argument.

>>> pyautogui.write('Hello world!') # prints out "Hello world!" instantly >>> pyautogui.write('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character 

You can only press single-character keys with write() , so you can’t press the Shift or F1 keys, for example.

The press(), keyDown(), and keyUp() Functions¶

To press these keys, call the press() function and pass it a string from the pyautogui.KEYBOARD_KEYS such as enter , esc , f1 . See KEYBOARD_KEYS.

>>> pyautogui.press('enter') # press the Enter key >>> pyautogui.press('f1') # press the F1 key >>> pyautogui.press('left') # press the left arrow key 

The press() function is really just a wrapper for the keyDown() and keyUp() functions, which simulate pressing a key down and then releasing it up. These functions can be called by themselves. For example, to press the left arrow key three times while holding down the Shift key, call the following:

>>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.keyUp('shift') # release the shift key 

To press multiple keys similar to what write() does, pass a list of strings to press() . For example:

>>> pyautogui.press(['left', 'left', 'left']) 

Or you can set how many presses left :

>>> pyautogui.press('left', presses=3) 

To add a delay interval in between each press, pass an int or float for the interval keyword argument.

The hold() Context Manager¶

To make holding a key convenient, the hold() function can be used as a context manager and passed a string from the pyautogui.KEYBOARD_KEYS such as shift , ctrl , alt , and this key will be held for the duration of the with context block. See KEYBOARD_KEYS.

>>> with pyautogui.hold('shift'): pyautogui.press(['left', 'left', 'left']) 

…is equivalent to this code:

>>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.keyUp('shift') # release the shift key 

The hotkey() Function¶

To make pressing hotkeys or keyboard shortcuts convenient, the hotkey() can be passed several key strings which will be pressed down in order, and then released in reverse order. This code:

>>> pyautogui.hotkey('ctrl', 'shift', 'esc') 

…is equivalent to this code:

>>> pyautogui.keyDown('ctrl') >>> pyautogui.keyDown('shift') >>> pyautogui.keyDown('esc') >>> pyautogui.keyUp('esc') >>> pyautogui.keyUp('shift') >>> pyautogui.keyUp('ctrl') 

To add a delay interval in between each press, pass an int or float for the interval keyword argument.

Читайте также:  Python list sort by multiple keys

KEYBOARD_KEYS¶

The following are the valid strings to pass to the press() , keyDown() , keyUp() , and hotkey() functions:

['\t', '\n', '\r', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', ', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ', '|', '>', '~', 'accept', 'add', 'alt', 'altleft', 'altright', 'apps', 'backspace', 'browserback', 'browserfavorites', 'browserforward', 'browserhome', 'browserrefresh', 'browsersearch', 'browserstop', 'capslock', 'clear', 'convert', 'ctrl', 'ctrlleft', 'ctrlright', 'decimal', 'del', 'delete', 'divide', 'down', 'end', 'enter', 'esc', 'escape', 'execute', 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f21', 'f22', 'f23', 'f24', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'final', 'fn', 'hanguel', 'hangul', 'hanja', 'help', 'home', 'insert', 'junja', 'kana', 'kanji', 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'left', 'modechange', 'multiply', 'nexttrack', 'nonconvert', 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', 'numlock', 'pagedown', 'pageup', 'pause', 'pgdn', 'pgup', 'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr', 'return', 'right', 'scrolllock', 'select', 'separator', 'shift', 'shiftleft', 'shiftright', 'sleep', 'space', 'stop', 'subtract', 'tab', 'up', 'volumedown', 'volumemute', 'volumeup', 'win', 'winleft', 'winright', 'yen', 'command', 'option', 'optionleft', 'optionright'] 

© Copyright 2019, Al Sweigart Revision 24d638dc .

Versions latest Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Работа бота: как симулировать нажатия клавиш в Python

Сегодня день рождения у Гвидо ван Россума, создателя Python. Поздравляем! Самое время поговорить о его детище и затронуть животрепещущую тему: как в Питоне имитировать нажатия клавиш при создании ботов. Суть бота — автоматическое выполнение действий, на которые не хочет тратить время человек. У программистов Python есть инструменты, позволяющие имитировать события клавиатуры и реагировать на них. Подборку таких инструментов вы и найдете ниже.

Зачем и кому это нужно

Поводы симулировать нажатие клавиш:

  • автоматизация — создание ботов для сайтов, приложений и игр. Пример: бот для автоматического заполнения форм или кормления/лечения игровых персонажей;
  • тестирование десктопных приложений — перебор возможных действий пользователя и реакций программы;
  • доступность — адаптация интерфейса для людей с ограниченными возможностями здоровья, в том числе за счёт эмуляции мыши (ведь без зрения ею не воспользуешься);
  • оптимизация — переназначение стандартных клавиш и/или замена недостающих кнопок физической клавиатуры.

Инструменты питониста для разных платформ

Для симуляции событий клавиатуры и мыши есть кроссплатформенный модуль PyUserInput , который работает поверх библиотек и фрейморков:

Для Windows также стоит отметить:

pyautoit — это Python API к средству автоматизации AutoIt;

pywinauto — набор модулей, который автоматизирует взаимодействие с Microsoft Windows GUI. Библиотека написана на чистом Python — простейшие её функции по обработке событий мыши и клавиатуры работают и в Linux. Но более сложные возможности для работы с текстом заточены именно под Windows и доступны только там.

Актуальные версии этих инструментов поддерживают Python 3, более ранние — Python 2.

Как это работает: примеры

В директории examples каталога pywinauto на GitHub собраны два десятка наглядных примеров по использованию библиотеки. С их помощью вы можете прямо сейчас создавать ботов, которые умеют устанавливать/удалять программы, скачивать web-страницы, перетаскивать файлы между окнами, пакетно обрабатывать изображения в MS Paint и решать другие задачи.

Новички оценят читаемость кода:

from pywinauto.application import Application # Запускаем целевое приложение - обычный блокнот app = Application().start("notepad.exe") # Выбираем пункт меню app.UntitledNotepad.menu_select("Help->About Notepad") # Симулируем клик app.AboutNotepad.OK.click() # Вводим текст app.UntitledNotepad.Edit.type_keys("Заработало!", with_spaces = True)

Хорошо? Представьте, что вам нужно перенастроить приложение из дефолтного состояния на N-ном количестве компьютеров — выбрать нужные пункты меню, заполнить нужные поля. Или вы тестируете свою программу вдоль и поперёк, чтобы выявить сбои при обращении к GUI. Скрипт, который вам потребуется, будет длиннее, чем в примере выше, но по сути усложнится незначительно.

Добавьте сюда возможность работать с любыми приложениями на Win32 GUI и виджетами под интерфейс MS UI Automation.

Устанавливается pywinauto как обычный пакет — через pip install — и автоматически ставит еще несколько полезных компонентов: библиотеку pyWin32 , COM-клиент и серверный фрейморк comtypes , библиотеку six , которая обеспечивает совместимость Python 2 (начиная с 2.6) и 3. Всё это пригодится начинающему разработчику не только для создания ботов, но и в разработке собственных программных продуктов.

Источник

Simulate Keyboard Inputs in Python

Simulate Keyboard Inputs in Python

  1. Simulate Keyboard Using the keyboard Library in Python
  2. Simulate Keyboard Using the PyAutoGUI Library in Python

Python is used for almost anything. Using Python, we can develop backends for web applications, backends for mobile applications, and APIs using free and open-source frameworks such as Django and Flask .

What’s more, Python programs also create efficient machine learning models using robust libraries such as Keras , NumPy , Tensorflow , and PyTorch , which plot various kinds of plots using Matplotlib , and much more.

In this article, we will see such use cases of Python. We will learn how to simulate or control the keyboard using Python.

We will talk about two open-source Python libraries, keyboard and PyAutoGUI , letting us control our keyboard using Python scripts.

Simulate Keyboard Using the keyboard Library in Python

The keyboard library is an open-source library to take control of your keyboard.

This library can listen to and send keyboard events, use hotkeys, support internationalization, and provide mouse support with the help of the mouse library, which we can download using pip install mouse or pip3 install mouse .

To install the keyboard library, use either of the following two pip commands.

pip install keyboard pip3 install keyboard 

Let us understand how to use this library to control a keyboard. Refer to the following Python code for a simple example that types some text.

import keyboard  keyboard.write("Python is an amazing programming language.") keyboard.press_and_release("enter") keyboard.press_and_release("shift+p") keyboard.press_and_release("y") keyboard.press_and_release("t") keyboard.press_and_release("h") keyboard.press_and_release("o") keyboard.press_and_release("n") 
Python is an amazing programming language. Python 

Before running the above code, take note of your text cursor or caret. The text above inside the output box will get typed there automatically.

The write() function will type whatever string is passed to this function as an argument. This function sends artificial keyboard events to the operating system, which gets further typed at the caret.

If any character is not available on the keyboard, explicit Unicode characters are typed instead. The press_and_release() function sends operating system events to perform hotkeys and type characters passed as arguments.

To understand more about this library, refer to its documentation here.

Simulate Keyboard Using the PyAutoGUI Library in Python

The PyAutoGUI library lets us write Python scripts to control the keyboard and mouse.

This library can move the mouse cursor and click over windows and applications, send key events to type characters and execute hotkeys, take screenshots, move, resize, minimize, maximize, and locate applications on the screen, and display alert messages, etc.

To install this library, use either of the following commands.

pip install pyautogui pip3 install pyautogui 

We can use the PyAutoGUI library for our use case. Refer to the following code for this.

import pyautogui  pyautogui.write("Python is an amazing programming language.") 
Python is an amazing programming language. 

As we can see, the write() function types character of the string passed as an argument at the caret. This function can only press single character keys such as alphabets and numbers.

This means we can not press keys such as Shift , Ctrl , Command , Alt , Option , F1 , and F3 . We can use the keyDown() and keyUp() methods to press such keys.

The keyDown() method presses a key and keeps holding it. And the keyUp() method releases a held key.

Refer to the following Python code for an example. Do not forget to note the position of your text cursor or caret.

import pyautogui  pyautogui.keyDown("shift") pyautogui.press("a") pyautogui.press("b") pyautogui.press("c") pyautogui.keyUp("shift") pyautogui.press("x") pyautogui.press("y") pyautogui.press("z") pyautogui.keyDown("shift") pyautogui.press("a") pyautogui.keyUp("shift") pyautogui.keyDown("shift") pyautogui.press("b") pyautogui.keyUp("shift") pyautogui.keyDown("shift") pyautogui.press("c") pyautogui.keyUp("shift") 

To press keys such as Shift + F , we can also use the press() method. This function will press whatever keys are passed as a string.

Behind the scenes, this function is just a wrapper for the keyDown() and keyUp() methods.

To understand more about this library, refer to its documentation here.

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article — Python Input

Источник

Оцените статью