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

让人想犯罪 __ 提交于 2019-12-22 18:41:09

问题


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)


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/41743087/python3-how-to-use-the-press-ctrlx-cut-and-ctrlv-using-pynput

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