Skip to content

Instantly share code, notes, and snippets.

@Jach
Created December 21, 2011 13:32
Show Gist options
  • Save Jach/1506056 to your computer and use it in GitHub Desktop.
Save Jach/1506056 to your computer and use it in GitHub Desktop.
System clipboard getter/setter
# Is this a stupid pattern?
def clipboard(text=None):
'''
Given no argument, returns the contents of the system clipboard or
None if empty.
Given an argument string, sets that as the value of the system clipboard and
returns the given string.
Note: The presence of calling this function will result in the system
clipboard being flushed on program termination.
'''
try:
_ = clipboard.win
except AttributeError:
import Tkinter
win = Tkinter.Tk()
win.withdraw()
clipboard.win = win
clipboard.TclError = Tkinter._tkinter.TclError
if text is None:
try:
return clipboard.win.selection_get(selection='CLIPBOARD')
except clipboard.TclError:
return None
else:
clipboard.win.clipboard_clear()
clipboard.win.clipboard_append(text)
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment