python3: how to use the press Ctrl+X (cut) and Ctrl+V using pynput?

following pynput documentation I tried this to "cut":

1: select some text in an editor

2: run this_code.py using a shortcut (without leaving the active windows)

from pynput.keyboard import Key, Controller
keyboard = Controller()
with keyboard.pressed(Key.ctrl):
    keyboard.press('x')
    keyboard.release('x')

The python console open actually print: ^X. The combination of keys are right but it doesn't do what it's suppose to do: cut the selected text store it in the clipboard. (I'm not interested to just store the clipboard content in a variable, I want a Ctrl+C)

I guess this answser will also solve the remaining part: Ctrl+V (to past some data which will be first inserted in the clipboard)


Solution 1:

I took 3 things into consideration:

  • since I am on a mac, the combination is Command+X instead of Ctrl+X

  • I can only make it work if I use keyboard.press (pressed doesn't work for me, don't know why)

  • For the special keys, I have to use their Key.value (so, Key.ctrl becomes Key.ctrl.value; Key.Shift becomes Key.Shift.value...)

In the end, this worked for me:

# I tested this code as it is in Mac OS
from pynput.keyboard import Key, Controller

keyboard = Controller()

# keyboard.press(Key.ctrl.value) #this would be for your key combination
keyboard.press(Key.cmd.value)
keyboard.press('x')
keyboard.release('x')
# keyboard.release(Key.ctrl.value) #this would be for your key combination
keyboard.release(Key.cmd.value)

Even though this question is a bit old, I was having this same problem and found a solution that worked for me. Might come in handy for someone in the future.