Python script to copy text to clipboard
323,515
Solution 1
See Pyperclip. Example (taken from Pyperclip site):
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()
Also, see Xerox. But it appears to have more dependencies.
Solution 2
On macOS, use subprocess.run
to pipe your text to pbcopy
:
import subprocess
data = "hello world"
subprocess.run("pbcopy", universal_newlines=True, input=data)
It will copy "hello world" to the clipboard.
Solution 3
To use native Python directories, use:
import subprocess
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
on Mac, instead:
import subprocess
def copy2clip(txt):
cmd='echo '+txt.strip()+'|pbcopy'
return subprocess.check_call(cmd, shell=True)
Then use:
copy2clip('This is on my clipboard!')
to call the function.
Solution 4
PyQt5:
from PyQt5.QtWidgets import QApplication
import sys
def main():
app = QApplication(sys.argv)
cb = QApplication.clipboard()
cb.clear(mode=cb.Clipboard )
cb.setText("Copy to ClipBoard", mode=cb.Clipboard)
# Text is now already in the clipboard, no need for further actions.
sys.exit()
if __name__ == "__main__":
main()
Solution 5
GTK3:
#!/usr/bin/python3
from gi.repository import Gtk, Gdk
class Hello(Gtk.Window):
def __init__(self):
super(Hello, self).__init__()
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text("hello world", -1)
Gtk.main_quit()
def main():
Hello()
Gtk.main()
if __name__ == "__main__":
main()
Related videos on Youtube
Author by
iamsiva11
Updated on June 06, 2021Comments
-
iamsiva11 about 3 years
I just need a python script that copies text to the clipboard.
After the script gets executed i need the output of the text to be pasted to another source. Is it possible to write a python script that does this job?
-
Junuxx about 12 yearsThis has been asked many times. Have you tried searching for Python+Windows+clipboard?
-
bitinerant almost 5 yearsIf you're looking to do this on Linux, see: How to share clipboard data between processes in GTK?.
-
Jason S about 4 yearsplease reopen: the linked question covers Windows; this is general.
-
-
Vincent Tjeng over 9 yearsI tried it on my system, and .setcb doesn't work, but .copy does. I'm using pyperclip 1.5.4 on py 2.7. Just in case someone runs into the same problems - and @robert, I'd love to hear why this syntax works on your system but doesn't on mine.
-
fnkr over 9 years.copy seems to be the offical one. github.com/asweigart/pyperclip
-
robert over 9 years@VincentTjeng updated
-
Chris Kerekes over 8 yearsWindows user can the clip command instead of pbcopy.
-
Vicky Dev about 8 yearsThis doesn't work on Ubuntu 14.04 LTS, please update your soluton for that immediately.
-
Tomasz Gandor about 8 years@VickyDev - it was developed on Ubuntu 14.04 LTS, and it works. Try
sudo apt-get install python-tk
, BTW. -
Nuno André almost 8 yearsA great code! github.com/terryyin/clipboard/blob/master/clipboard.py
-
Leonidas A almost 8 yearsDon't bother with this, it just uses
pyperclip
. Use that instead. -
Vitaly Zdanevich over 7 yearsDoes not working for me - clipboard have the same data, Python 3.5.2
-
Admin over 7 yearsCalledProcessError Traceback (most recent call last) <ipython-input-91-c0c14042eb28> in <module>() 4 cmd='echo '+txt.strip()+'|clip' 5 return subprocess.check_call(cmd, shell=True) ----> 6 copy2clip('This is on my clipboard!') <ipython-input-91-c0c14042eb28> in copy2clip(txt) 3 def copy2clip(txt): 4 cmd='echo '+txt.strip()+'|clip' ----> 5 return subprocess.check_call(cmd, shell=True) ... CalledProcessError: Command 'echo This is on my clipboard!|clip' returned non-zero exit status 127
-
Jean-François Fabre about 6 yearsthis works, but on windows,
clip
is a windows only command (and sometimes it's not part of the system, you have to download & install it manually on WinXP) -
Saelyth over 5 yearsIf you are using
QApplication.clipboard()
you don't need to importQClipboard
. -
Seaky Lone over 5 yearsSeems good but has an extra '\n'.
-
Niko about 5 yearsOne thing is the extra '\n' and the other is that I had problems when copying linux commands, e.g. 'kill 1026 && kill 982'. pyperclip did the job in the end.
-
Hatshepsut about 5 yearsThis is a security hazard, because it is vulnerable to shell injection attacks.
-
xtluo about 5 yearsIf the copied text doesn't persist after running from the script, refer to this issue for the solution.
-
Shmuel Kamensky about 4 years@Hatshepsut You can write the data to a temporary file and feed clip the file path instead. This both mitigates the shell injection security risk and also simplifies shell character escape issues ("if you use the method in the answer and want to copy text with double quotes, it becomes more complex")
-
Conner M. almost 4 yearscmd window pops up briefly in windows
-
Palbitt almost 4 years@O.rka Same for me. I'm on Debian Linux.
-
Soren Bjornstad over 3 years-1. Shelling out is a sensible way to handle this, but as @Hatshepsut says the sample code is extremely dangerous and unreliable, even if someone is not actively trying to hack something. There are all kinds of things you could have on your clipboard that could inadvertently run commands or at least cause syntax errors.
-
Lucas Vazquez over 3 yearsI use xsel in linux.
echo 'CUSTOM STRING' | xsel --clipboard --input
. Usage example with pythonsubprocess.Popen(['/bin/sh', '-c', f'echo "{123}" | xsel --clipboard --input'])
-
Raniz over 2 yearsYou can
xclip
in Linux instead ofpbcopy
-
RedGlyph over 2 yearsWith Windows 10, this just freezes when trying to paste, so I don't recommend
-
RedGlyph over 2 years"No module named 'gi'" - I suspect this is not a standard library
-
JoeW about 2 yearsThis also works really great if using PySimpleGUIQt
cb = sg.QtGui.QClipboard() cb.clear(mode=cb.Clipboard) cb.setText(values["-DATA-"])