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.
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 usingctypes
,pywin32
, or other libraries. Here I've chosenpyperclip
:You could import
pyperclip
and usepyperclip.copy('my text I want copied')
and then usepyperclip.paste()
to paste the text wherever you want it to go. You can find a reference here.Well... Here it is:
Tk().clipboard_get()
returns the current text in the clipboard.And you need to use
pyautogui.hotkey('ctrl', 'c')
first.What soundstripe posted is valid, but doesn't take into account copying null values when there was a previous value copied. I've included an additional line that clears the clipboard so null-valued copies remain null-valued: