Python3:如何使用Pynput使用Ctrl + X(剪切)和Ctrl + V? [英] python3: how to use the press Ctrl+X (cut) and Ctrl+V using pynput?

查看:1022
本文介绍了Python3:如何使用Pynput使用Ctrl + X(剪切)和Ctrl + V?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循 pynput文档,我尝试这样做是为了剪切":

following pynput documentation I tried this to "cut":

1:在编辑器中选择一些文本

1: select some text in an editor

2:使用快捷方式运行this_code.py(不离开活动窗口)

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')

打开的python控制台实际上打印:^ X.组合键是正确的,但是它没有做应该做的事情:剪切所选的文本并将其存储在剪贴板中. (我不只是将剪贴板内容存储在变量中,我想要Ctrl + C)

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)

我想这答案也将解决其余部分:Ctrl + V(删除将首先插入剪贴板的某些数据)

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

推荐答案

我考虑了3件事:

  • 因为我在Mac上,所以组合键是Command + X而不是Ctrl + X

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

仅当我使用keyboard.press时,它才能正常工作(被按下对我不起作用,不知道为什么)

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

对于特殊键,我必须使用它们的Key.value(因此,Key.ctrl变成Key.ctrl.value; Key.Shift变成Key.Shift.value ...)

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

最后,这对我有用:

# 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.

这篇关于Python3:如何使用Pynput使用Ctrl + X(剪切)和Ctrl + V?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆