Как имитировать нажатие клавиши python
Перейти к содержимому

Как имитировать нажатие клавиши python

  • автор:

Simulate Keypresses In Python

This demonstrates how to press keys with Python. Using pynput we are able to simulate key presses into any window. This will show you how to press and release a key, type special keys and type a sentence.

If you haven’t used or setup pip before, go to my tutorial at how-to-setup-pythons-pip to setup pip.

We will be using the pynput module to listen to mouse events. To install this module execute pip install pynput in cmd. Watch the output to make sure no errors have occurred; it will tell you when the module has been successfully installed.

Installing pynput

To double-check that it was installed successfully, open up IDLE and execute the command import pynput ; no errors should occur.

Testing pynput

Create a new script and save it somewhere so you can easily run the script. Import Key and Controller from pynput.keyboard .

Make a variable called keyboard and set it to an instance of Controller . Now using the keyboard variable we can press and release keys.

Pressing and Releasing Keys

Using keyboard.press we can press keys and with keyboard.release we can release a key. This allows us to type a key by pressing and releasing. You can only supply this method with one key at a time. Here is an example of how to type the letter ‘a’.

Pressing and Releasing Special Keys

For special keys that can’t be put into a string like shift or control, you will need to refer to the page here to look at the Key class for supported keys. Using these in the press or release methods will press/release the key matching it. For example, if I wanted to press the Windows key, I would look at that page for the key. ‘cmd’ has the description «A generic command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key» which is what I am looking for. Now for the code.

This method also allows us to press a key while holding another key, for example, ctrl+c to copy. To do this we will need to press ctrl, press and release c and then release ctrl.

Here are a few other common special keys:

    : Left ALT : Backspace : Left Ctrl : Delete : Enter : Escape : F1 : F5 : Play/Pause : Page Down : Up Arrow Key
  • The rest can be found in the pynput docs for the Key class.

Typing Multiple Keys

A cool feature supplied by the class is the type method. This method allows us to type more than one key at a time but it has to be a string of characters. So if we wanted to type «Nitratine» we would execute:

This method does also support spaces but when it comes to enters, use a new line character (\n) and a tab character (\t) for tabs.

Putting A Random Delay Between Each Keypress

To put a random delay between each keypress, you can use time.sleep with a random number passed to it. Here is a small example function I made:

Common Issues and Questions

How can I use the keyboard and mouse controllers at the same time?

When you import the classes, Controller will be set to the last one imported. To show what the issue was, ask yourself, what controller did you use to set the mouse and what one to set the keyboard? You would have used the same, but they need to be from the different classes. So then you should use:

Now when you want to use the controller for the mouse use MouseController and KeyboardController for the keyboard.

ModuleNotFoundError/ImportError : No module named ‘pynput’

Did you install pynput? This error will not occur if you installed it properly. If you have multiple versions of Python, make sure you are installing pynput on the same version as what you are running the script with.

I got a SyntaxError

Syntax errors are caused by you and there is nothing I can offer to fix it apart from telling you to read the error. They always say where the error is in the output using a ^. Generally, people that get this issue have incorrect indentation, brackets in the wrong place or something spelt wrong. You can read about SyntaxError on Python’s docs here.

The Key Presses Work in Notepad But Not My Game

pynput uses a Win32API function called SendInput . The SendInput function will insert input events into the same queue as a hardware device but the events are marked with a LLMHF_INJECTED flag that can be detected by hooks and then filtered. To avoid this flag you probably have to write a custom driver (ref: stackoverflow/Anders).

It would be ideal for most games to look for these events if they want to reduce ‘bot’ activity as it stops packages like these being used.

In github.com/Gautam-J/Self-Driving-Car I had seen that the file directkeys.py contained the following:

The license for this piece of code can be found here.

This file demonstrates how we can press keys using DirectX key codes. The link in the file no longer exists but it can still be found on the wayback machine. This page provides other codes for keys that can be simulated.

Unfortunately it will only work on Windows (due to the usage of ctypes.windll ) but some may find that it solves their issues with the LLMHF_INJECTED flag.

Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.

Guide to Python's keyboard Module

Python is one of the most suitable languages for automating tasks. Whether it's repeatable (ethical) web scraping after some time period, starting some programs on a computer start up, or automating sending mundane e-mails, Python has a lot of modules that make your life easier.

One of these is a module called keyboard , and it takes full control of your keyboard. With this module, you can type out anything, create hot-keys, create abbreviations, block the keyboard, wait for input, etc.

In this guide, we'll take a look at how to set up and use the keyboard module in Python.

Note: Applications working with automating human-like processes should be developed ethically and responsibly. The keyboard module is made to be very observable, and thus makes it both discouraged and transparent if anyone's using it to create keyloggers or malicious bots.

Installing the keyboard Module

Note: The version of Python used in this guide is 3.8. However, the keyboard module can work with both Python 2.x and Python 3.x.

If you're using Linnux, in order to use this library, you must install it as root . If you don't, you'll get an:

Also, when running your script, you should run it with root privileges:

On Windows and MacOS, as the privileges work much differently — you can install it simply via pip and run the scripts:

Note: For MacOS, you might have to allow the Terminal or other apps to change the state of your machine, such as by typing. Also keep in mind that as of September 2021, the library is still experimental on MacOS.

The keyboard Module's Functions

There are a lot of functions in this module that can be used to simulate keyboard actions.

  • keyboard.write(message, [delay]) — writes a message, with or without a delay.
  • keyboard.wait(key) — blocks the program until the key is pressed. The key is passed as a string ('space', 'esc', etc.)
  • keyboard.press(key) — presses a key and holds until the release(key) function is called.
  • keyboard.release(key) — releases a key.
  • keyboard.send(key) — presses and releases a key.
  • keyboard.add_hotkey(hotkey, function) — creates a hotkey which when pressed, executes a function .
  • keyboard.record(key) — records keyboard activity until key is pressed.
  • keyboard.play(recorded_events, [speed_factor]) — replays events recorded with keyboard.record(key) function, with an optional speed_factor .

We'll go through all of these, though, here's a quick example:

The Hello message appears on the screen, in the terminal, as if you've written it. You can automate a command very easily, and create a hotkey alias for it. Here's a (crude) example of exiting the Python REPL, writing a curl commmand and executing it:

keyboard's write() and wait() Functions

The write() command writes a message, as we've seen before, with an optional delay in the start. If no delay is set, writing is instant. It's very nicely combined with the wait() function, which awaits a certain key to be pressed.

For instance, we can create a make-shift macro, tied to, say 1 , which responds to that input with a new message. Note that there's an actual way to create hotkeys instead of this, which we'll cover later.

We'll create an infinite True loop to check for the key being pressed, and you can run the script in the background:

Note: Special characters are not supported by this function, so if you add, say, ! — you'll get hit with a StopIteration exception.

keyboard's press(), release() Functions

Since it's hard to simulate press() and release() so that the actions are visible, we'll also see record() and play() in action.

The press() function presses a key and releases it when you call release() on the same key. Note that you can't sleep() for some time to simulate holding down a key:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

However, you can hold down some special keys, such as [SHIFT] or [CTRL] this way:

keyboard's record() and play() Functions

It's not always about inputting new keys in — sometimes, you'd like to record what's going on and play it back. Keep in mind that you'll need administrator privileges to record any input like this, as the technology can easily be used to create key loggers.

The record() function accepts a trigger key, until which it records, and returns a sequence of events of type KeyboardEvent . You can then chuck this sequence of events into the play() function, which faithfully replays them, with an optional speed_factor argument that acts as a multiplier for the speed of the original events:

If we're to print the recorded_events , they'd look something like:

The effects of these methods are best seen as a gif or recreated on your machine. For instance, a sequence of writing a message, deleting it and writing a different one instead:

keyboard's send() function

The send() function encompasses press() and release() together, and is used for single keys, unlike write() which is used for entire sentences:

Once s is pressed, the w and a keys are replayed.

The press() function can also accept combinations of pressed keys. You can send a combination of "ctrl+shift+s" for instance and the dialogue for saving a file should pop up, if you're in an application that supports that operation:

Though, this isn't the right way to add hotkeys. Rather, you can use the add_hotkey() function.

keyboard's add_abbreviation() Function

The add_abbreviation() function is a pretty nifty one, as it allows you to define abbreviations for long inputs, and replaces the abbreviated versions with the saved full versions.

For instance, similar to how services like Google save your email for most input forms, you can create your own abbreviation and trigger it via [SPACE] :

While running, if you type @ followed by a [SPACE] — the long-form input will replace the typed @ .

keyboard's add_hotkey() Function

The add_hotkey() function accepts a hotkey you'd like to save, or a combination of keys, and a function. It's easy to pass in anonymous lambda functions here, though you can also add named functions.

For instance, let's add a hotkey for CTRL+j , which triggers a lambda function that logs this:

The hotkey, ctrl+alt+p , is saved and when you press this combination, you should see the output of the lambda.

Conclusion

The keyboard module is a lightweight and simple library used for simulating keystrokes and simple automation in Python. It's not very feature-rich, but can be used to automate some of the tasks you might be performing in your day-to-day work, or simply for a bit of fun.

A more mature, powerful module that can be used as an alternative is pynput.

Simulate Keyboard Inputs in Python

Simulate Keyboard Inputs 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.

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.

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.

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

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.

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.

keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

Features

  • Global event hook on all keyboards (captures keys regardless of focus).
  • Listen and send keyboard events.
  • Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!).
  • Pure Python, no C modules to be compiled.
  • Zero dependencies. Trivial to install and deploy, just copy the files.
  • Python 2 and 3.
  • Complex hotkey support (e.g. ctrl+shift+m, ctrl+space ) with controllable timeout.
  • Includes high level API (e.g. record and play, add_abbreviation).
  • Maps keys as they actually are in your layout, with full internationalization support (e.g. Ctrl+ç ).
  • Events automatically captured in separate thread, doesn’t block main program.
  • Tested and documented.
  • Doesn’t break accented dead keys (I’m looking at you, pyHook).
  • Mouse support available via project mouse ( pip install mouse ).

Usage

or clone the repository (no installation required, source files are sufficient):

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *