Skip to content
Advertisement

How can I send a keyboard interrupt ctrl+] to the terminal using a Python program?

I’m currently working on a ESP32 project in which there is a command named ‘idf.py monitor’. This command outputs strings into the bash only after the keyboard interruption ‘ctrl+]’.

It’s annoying to finish the program by tabbing ‘ctrl+]’ everytime. So that I wrote a python script to execute the command automatically.

import os
command='idf.py monitor'
r=os.popen(command) #execute the command
context=r.readlines() # get the command output
print(context)

However, the ‘print’ function only works after the key interrupt ‘ctrl+]’.

So my question is: How can I write a python script that can send the keyinterrupt ‘ctrl+]’ to my shell automatically?

(I tried using process.kill() or process.terminate() which send ‘ctrl+c’, but that doesn’t work)

Advertisement

Answer

You can use a module named as keyboard

  1. pip install keyboard
import keyboard
keyboard.press_and_release('ctrl+]')
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement