1

我正在使用pynput库编写一个 python 脚本,我想在其中选择特定长度的文本。

为此,我首先按 shift,然后按多次左箭头键。以便选择光标 id 左侧的文本,并可进一步用于复制目的。

这是我的代码:

from pynput import keyboard
from pynput.keyboard import Controller

keyboard_controller = Controller()
with keyboard_controller.pressed(keyboard.Key.shift_l):
    keyboard_controller.press(keyboard.Key.left)
    keyboard_controller.release(keyboard.Key.left)
    keyboard_controller.press(keyboard.Key.left)
    keyboard_controller.release(keyboard.Key.left)
    keyboard_controller.press(keyboard.Key.left)
    keyboard_controller.release(keyboard.Key.left)

这会将我的光标向左移动 3 步,但即使按下 shift,文本也不会被选中。我在这里缺少什么?

编辑:

操作系统:Windows 10

环境:Python 3.6.5

这是我的 vs 代码中发生的事情的演示。 在此处输入图像描述

4

2 回答 2

0

我刚刚玩弄了 pynput 和 pyautogui,最后找到了一个使用 pynput 的组合,可以完成这个 shift 热键功能。我在代码中使用 page_down 而不是箭头键,但我确认两者都有效。出于某种原因,如果同时按下 shift 键和 shift_r 键,则可以通过移动光标来突出显示文本。

设置:

from pynput.keyboard import Key, Controller

keyboard = Controller()

代码:

keyboard.press(Key.shift)
keyboard.press(Key.shift_r)
keyboard.press(Key.page_down)  # or keyboard.press(Key.left)
keyboard.release(Key.page_down)  # or keyboard.release(Key.left)
keyboard.release(Key.shift_r)
keyboard.release(Key.shift)
于 2019-08-06T15:52:47.090 回答
0

也许试试这个?

from pynput.keyboard import Key
from pynput.keyboard import Controller

keyboard = Controller()

选项1:

with keyboard.pressed(Key.shift):
    keyboard.press(Key.left)
    keyboard.release(Key.left)
    keyboard.press(Key.left)
    keyboard.release(Key.left)

选项 2:

keyboard.press(Key.shift)
keyboard.press(Key.left)
keyboard.release(Key.left)
keyboard.press(Key.left)
keyboard.release(Key.left)
keyboard.release(Key.shift)

选项 3:

keyboard.press(Key.shift.value)
keyboard.press(Key.left.value)
keyboard.release(Key.left.value)
keyboard.press(Key.left.value)
keyboard.release(Key.left.value)
keyboard.release(Key.shift.value)

这是它在我的机器上工作的视频证明:)

在此处输入图像描述

于 2018-10-14T05:52:19.113 回答