Python Script to Copy Text to Clipboard

How do I copy a string to the clipboard?

Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

If all you need is to put some text to system clipboard, this will do it:

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

And that's all, no need to mess around with platform-specific third-party libraries.

If you are using Python 3, replace TKinter with tkinter.

How do I copy lines from a text file onto the clipboard in python

If you have pip, you can install a module called pyperclip.

On macOS:

pip3 install pyperclip (sometimes add --user onto the end)

On Windows:

pip install pyperclip

Now that you have this installed, you need to read the file with file.read() and store it into a variable, then call pyperclip.copy(variablename).

Full code:

import pyperclip

with open("path/to/file.txt") as f:
data = f.read()
pyperclip.copy(data)

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

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)

Copy text from textarea to clipboard - Python

You can also use navigator.clipboard. https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard

function copyToClipboard() {
let clip = navigator.clipboard;
if (clip === undefined) {
console.log(
"Upgrade your browser to use the clipboard feature.",
);
} else {
navigator.clipboard.writeText(document.getElementById('my_input').value);

}
}
<input id='my_input' />

<button onClick='copyToClipboard()' >
Click me
</button>


Related Topics



Leave a reply



Submit