290

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?

4

8 Answers 8

355

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.

5
  • 2
    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. Sep 28, 2014 at 18:20
  • 1
    .copy seems to be the offical one. github.com/asweigart/pyperclip
    – fnkr
    Oct 17, 2014 at 19:50
  • If the copied text doesn't persist after running from the script, refer to this issue for the solution.
    – xtluo
    Jun 10, 2019 at 7:28
  • xerox worked for me on kubunutu 20.04; see here. Mar 27, 2023 at 17:27
  • Important note mentioned in the Readme: Currently only handles plaintext. On Windows, no additional modules are needed. On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os. On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run "sudo apt-get install xclip" or "sudo apt-get install xsel" (Note: xsel does not always seem to work.) Otherwise on Linux, you will need the gtk or PyQt4 modules installed. So check for dependencies on your platform/system. Jun 27, 2023 at 4:22
147

On macOS, use subprocess.run to pipe your text to pbcopy:

import subprocess 
data = "hello world"
subprocess.run("pbcopy", text=True, input=data)

It will copy "hello world" to the clipboard.

6
  • 22
    Windows user can the clip command instead of pbcopy. Feb 25, 2016 at 23:27
  • 5
    Does not working for me - clipboard have the same data, Python 3.5.2 Oct 5, 2016 at 10:34
  • cmd window pops up briefly in windows
    – Conner M.
    Jul 14, 2020 at 19:07
  • 3
    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']) Feb 25, 2021 at 2:12
  • 1
    This approach worked better for me vs depending on a library. I don't want to add "unnecessary" dependencies to my venvs/conda envs. Sep 19, 2023 at 20:04
31

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.

11
  • 2
    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
    – anon
    Dec 16, 2016 at 19:28
  • 3
    Seems good but has an extra '\n'.
    – Seaky Lone
    Jan 20, 2019 at 21:22
  • 1
    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.
    – Niko
    Apr 25, 2019 at 8:59
  • 14
    This is a security hazard, because it is vulnerable to shell injection attacks.
    – Hatshepsut
    May 8, 2019 at 3:50
  • 3
    -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. Oct 3, 2020 at 17:50
14

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()
2
  • 2
    If you are using QApplication.clipboard() you don't need to import QClipboard.
    – Saelyth
    Jan 16, 2019 at 0:10
  • This also works really great if using PySimpleGUIQt cb = sg.QtGui.QClipboard() cb.clear(mode=cb.Clipboard) cb.setText(values["-DATA-"])
    – JoeW
    Jun 12, 2022 at 13:26
6

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()
1
  • "No module named 'gi'" - I suspect this is not a standard library
    – RedGlyph
    Jan 8, 2022 at 14:28
5

I try this clipboard 0.0.4 and it works well.

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard
2
2

One more answer to improve on: https://stackoverflow.com/a/4203897/2804197 and https://stackoverflow.com/a/25476462/1338797 (Tkinter).

Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

import sys

try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()

if len(sys.argv) < 2:
    data = sys.stdin.read()
else:
    data = ' '.join(sys.argv[1:])

r.clipboard_append(data)

if sys.platform != 'win32':
    if len(sys.argv) > 1:
        raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
    else:
        # stdin already read; use GUI to exit
        print('Data was copied into clipboard. Paste, then close popup to exit...')
        r.deiconify()
        r.mainloop()
else:
    r.destroy()

This showcases:

  • importing Tk across Py2 and Py3
  • raw_input and print() compatibility
  • "unhiding" Tk root window when needed
  • waiting for exit on Linux in two different ways.
3
  • This doesn't work on Ubuntu 14.04 LTS, please update your soluton for that immediately.
    – Vicky Dev
    May 10, 2016 at 6:47
  • @VickyDev - it was developed on Ubuntu 14.04 LTS, and it works. Try sudo apt-get install python-tk, BTW. May 10, 2016 at 12:45
  • With Windows 10, this just freezes when trying to paste, so I don't recommend
    – RedGlyph
    Dec 21, 2021 at 14:01
2

This is an altered version of @Martin Thoma's answer for GTK3. I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.

#!/usr/bin/python3

from gi.repository import Gtk, Gdk
import sys
from time import sleep

class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        
        clipboardText = sys.argv[1]
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(clipboardText, -1)
        clipboard.store()


def main():
    Hello()
    
    

if __name__ == "__main__":
    main()

You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.

On a fresh ubuntu 16.04 installation, I found that I had to install the python-gobject package for it to work without a module import error.

Not the answer you're looking for? Browse other questions tagged or ask your own question.