Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy highlighted text to clipboard, then use the clipboard to append it to a list

I'm trying to automate some actions in a browser or a word processor with pyautogui module for Python 3 (Windows 10).

There is a highlighted text in a browser.

text

the following script should print the highlighted text

import pyautogui as pya

# double clicks on a position of the cursor
pya.doubleClick(pya.position())

list = []
# a function copy_clipboard() should be called here
var = copy_clipboard()
list.append(var) 
print(list)

The output should be:

[text]

So how should the function copy_clipboard() look like? Thank you for your help.

like image 323
Степан Смирнов Avatar asked Jul 24 '18 18:07

Степан Смирнов


1 Answers

The keyboard combo Ctrl+C handles copying what is highlighted in most apps, and should work fine for you. This part is easy with pyautogui. For getting the clipboard contents programmatically, as others have mentioned, you could implement it using ctypes, pywin32, or other libraries. Here I've chosen pyperclip:

import pyautogui as pya
import pyperclip  # handy cross-platform clipboard text handler
import time

def copy_clipboard():
    pya.hotkey('ctrl', 'c')
    time.sleep(.01)  # ctrl-c is usually very fast but your program may execute faster
    return pyperclip.paste()

# double clicks on a position of the cursor
pya.doubleClick(pya.position())

list = []
var = copy_clipboard()
list.append(var) 
print(list)
like image 91
soundstripe Avatar answered Sep 18 '22 00:09

soundstripe