Skip to content

Instantly share code, notes, and snippets.

@adam-p
Created November 30, 2012 01:37
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adam-p/4173174 to your computer and use it in GitHub Desktop.
Save adam-p/4173174 to your computer and use it in GitHub Desktop.
Python function to copy text to clipboard (so far only supports Windows).
import sys
import subprocess
def copy(s):
if sys.platform == 'win32' or sys.platform == 'cygwin':
subprocess.Popen(['clip'], stdin=subprocess.PIPE).communicate(s)
else:
raise Exception('Platform not supported')
'''
# On Windows, with pywin32 installed, this can also be done like so:
import win32clipboard as cb
def copy(s):
cb.OpenClipboard()
cb.EmptyClipboard()
cb.SetClipboardData(cb.CF_TEXT, str(s))
cb.CloseClipboard()
'''
@venkywarriors
Copy link

does it work for python 3.x with windows 64 bit

@nickymarino
Copy link

nickymarino commented Jun 21, 2018

I was able to use python 3.6.5 using Windows 10 64 bit with this, but I had to add encoding='utf8' as an argument to Popen to pass strings to the function rather than a byte array.

I think you can also easily extend this to macOS using pbcopy in place of clip as well.

@asweigart
Copy link

You might want to take a look (or contribute to) the pyperclip project, which does copy/paste functions for Windows/Mac/Linux.

@danielrossyamitrano
Copy link

Works perfectly fine on my Windows 10 64-bit and Python 3.8 64-bit, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment