6

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)

4 Answers 4

6

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.

1
  • 1
    How could you select the text?
    – Kaushal28
    Oct 14, 2018 at 11:07
1

First install pyautogui with:
pip install pyautogui

#Then in your code write:

import pyautogui

pyautogui.hotkey('ctrl', 'v')
1
  • I believe the OP specifically wanted pynput, not pyautogui? Jan 23, 2022 at 18:57
0

I think you should use keyboard.type(msg) instead of keyboard.press(key)

0

I tried it on my side, and I think the problem is that you are using Key.ctrl as the argument for keyboard.pressed() on line 3.

Instead of that you should be using Key.ctrl.value.

So, the correct version of the code you have given would be:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.