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

﹥>﹥吖頭↗ 提交于 2019-12-06 12:26:24
wazoowazoo

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!