J. *_*oes 6 python keyboard copy-paste key python-3.x
根据pynput 文档,我尝试“剪切”:
1:在编辑器中选择一些文本
2:使用快捷方式运行this_code.py(不离开活动窗口)
from pynput.keyboard import Key, Controller
keyboard = Controller()
with keyboard.pressed(Key.ctrl):
keyboard.press('x')
keyboard.release('x')
Run Code Online (Sandbox Code Playgroud)
python控制台打开实际上打印:^X。键的组合是正确的,但它没有执行它应该执行的操作:剪切选定的文本并将其存储在剪贴板中。(我不想只将剪贴板内容存储在变量中,我想要 Ctrl+C)
我想这个答案也将解决剩余部分:Ctrl+V(过去一些将首先插入剪贴板的数据)
小智 6
我考虑了三件事:
因为我使用的是 Mac,所以组合是 Command+X 而不是 Ctrl+X
我只能在使用 Keyboard.press 时才能使其工作(按下对我不起作用,不知道为什么)
对于特殊键,我必须使用它们的 Key.value (因此,Key.ctrl 变为 Key.ctrl.value;Key.Shift 变为 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)
Run Code Online (Sandbox Code Playgroud)
尽管这个问题有点老了,但我也遇到了同样的问题,并找到了适合我的解决方案。可能对将来的某人有用。