This code uses self in the context of a class, typically an extension.

Subscribe to Keyboard Events

import omni.appwindow
import carb.input

app_window = omni.appwindow.get_default_app_window()
self.keyboard = app_window.get_keyboard()
input = carb.input.acquire_input_interface()
self.keyboard_sub_id = input.subscribe_to_keyboard_events(self.keyboard, self.on_keyboard_input)

Handle Keyboard Events

from carb.input import KeyboardEventType

def on_keyboard_input(self, e):
    if e.input == carb.input.KeyboardInput.W:
        if e.type == KeyboardEventType.KEY_PRESS or e.type == KeyboardEventType.KEY_REPEAT:
        elif e.type == KeyboardEventType.KEY_RELEASE:

Unsubscribe the Keyboard Event Handler

When you are done using it you should unsubscribe from the event handling using one of these two methods.

import carb.input

input = carb.input.acquire_input_interface()
keyboard = app_window.get_keyboard()
input.unsubscribe_to_keyboard_events(keyboard, self.keyboard_sub_id)

# or just...
self.keyboard_sub_id = None