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()
Share:
323,515

Related videos on Youtube

iamsiva11
Author by

iamsiva11

Updated on June 06, 2021

Comments

  • iamsiva11
    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?

  • Vincent Tjeng
    Vincent Tjeng over 9 years
    I 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
    fnkr over 9 years
    .copy seems to be the offical one. github.com/asweigart/pyperclip
  • robert
    robert over 9 years
    @VincentTjeng updated
  • Chris Kerekes
    Chris Kerekes over 8 years
    Windows user can the clip command instead of pbcopy.
  • Vicky Dev
    Vicky Dev about 8 years
    This doesn't work on Ubuntu 14.04 LTS, please update your soluton for that immediately.
  • Tomasz Gandor
    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é
    Nuno André almost 8 years
  • Leonidas A
    Leonidas A almost 8 years
    Don't bother with this, it just uses pyperclip. Use that instead.
  • Vitaly Zdanevich
    Vitaly Zdanevich over 7 years
    Does not working for me - clipboard have the same data, Python 3.5.2
  • Admin
    Admin over 7 years
    CalledProcessError 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
    Jean-François Fabre about 6 years
    this 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
    Saelyth over 5 years
    If you are using QApplication.clipboard() you don't need to import QClipboard.
  • Seaky Lone
    Seaky Lone over 5 years
    Seems good but has an extra '\n'.
  • Niko
    Niko about 5 years
    One 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
    Hatshepsut about 5 years
    This is a security hazard, because it is vulnerable to shell injection attacks.
  • xtluo
    xtluo about 5 years
    If the copied text doesn't persist after running from the script, refer to this issue for the solution.
  • Shmuel Kamensky
    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.
    Conner M. almost 4 years
    cmd window pops up briefly in windows
  • Palbitt
    Palbitt almost 4 years
    @O.rka Same for me. I'm on Debian Linux.
  • Soren Bjornstad
    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
    Lucas Vazquez over 3 years
    I use xsel in linux. echo 'CUSTOM STRING' | xsel --clipboard --input . Usage example with python subprocess.Popen(['/bin/sh', '-c', f'echo "{123}" | xsel --clipboard --input'])
  • Raniz
    Raniz over 2 years
    You can xclip in Linux instead of pbcopy
  • RedGlyph
    RedGlyph over 2 years
    With Windows 10, this just freezes when trying to paste, so I don't recommend
  • RedGlyph
    RedGlyph over 2 years
    "No module named 'gi'" - I suspect this is not a standard library
  • JoeW
    JoeW about 2 years
    This also works really great if using PySimpleGUIQt cb = sg.QtGui.QClipboard() cb.clear(mode=cb.Clipboard) cb.setText(values["-DATA-"])