I installed a win32com.client module win32com.client In it, you can make an imitation of keystrokes (A la Ctrl + C ):

 shell = win32com.client.Dispatch('WScript.Shell') shell.SendKeys('^a^x') 

However, one very strange feature appeared in the process: all these imitations of pressing are launched in the background thread. In my case, this is unacceptable. How to make so that all program waited, while pressing will be simulated? I tried threading - it turned out, but the program is now instead of 0.1s. 3c works, which is unacceptable.

  • And why do you imitate keystrokes? - Andrio Skur
  • @AndrioSkur in general, the program should copy the text from any text field (whether it be a comment input field on Stackoverflow or a message input field in Telegram), perform some operations on this line and paste it back. I decided for this purpose to use the keystroke simulation Ctrl + A, Ctrl + X and Ctrl + V. And I get the string from the clipboard (using pyperclip) - garbart
  • 1. Have you tried to use multiprocessing instead of threading? (Just using multiprocessing creates threads that the system sees, not just a python) 2. Show your version with threading - Andrio Skur
  • @AndrioSkur, the multiprocessing module spawns processes, not threads. The threads generated by threading are quite normal from the point of view of the OS (you can run top or any other dispatcher and make sure), the system “sees” them quite normally - each thread, at least in CPython, has an OS thread. Moreover, new threads are generated not by some kind of magic, but by system libraries, for example, pthreads . - m9_psy
  • @ m9_psy @AndrioSkur but the question is still open: how to make the program wait until imitation is performed without using threading ? Unfortunately, multiprocessing did not help. - garbart

1 answer 1

If the use of the win32com.client module is not essential, you can use the more convenient pywinauto (it is waiting for sending keys to the application):

 from pywinauto.application import Application from datetime import datetime # Запускаем блокнот app = Application().start("notepad") # Можно посылать спецсимволы # app.UntitledNotepad.Edit.type_keys("^a^v") # app.UntitledNotepad.Edit.type_keys("{VK_F5}") # Вставим текущее время для проверки app.UntitledNotepad.Edit.type_keys(datetime.now().strftime("%H:%M:%S.%f")) print(datetime.now().strftime("%H:%M:%S.%f")) 

Keystroke Emulation Documentation

Tested in Python 3.6 with fresh pywinauto , Windows 7 64-bit