Using clipboard from Python

Updated TrustyTony 0 Tallied Votes 2K Views Share

This came up, maybe it is usefull to somebody. Later I plan to do a managing context interface to withstatement for this.

# Based on http://snippets.dzone.com/posts/show/724:
import win32clipboard as w 
import win32con
from time import sleep

def get_text(): 
    w.OpenClipboard() 
    d = w.GetClipboardData(win32con.CF_TEXT) 
    w.CloseClipboard() 
    return d 

def set_text(to_put, the_type=w.CF_TEXT): 
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(the_type,to_put) 
    w.CloseClipboard()

def clipboard_wait():
    set_text('')
    # wait text to enter clipboard
    while not (get_text()):
        sleep(0.1)

    return get_text()

print(clipboard_wait())
TrustyTony 888 pyMod Team Colleague Featured Poster
OS independent version

But the referenced source from Activestate had response, that referes to StackOverflow question that has piece of code with tkinter, which is mayby better, even sometimes I get this error:

Traceback (most recent call last):
  File "I:\test\clip_tk.py", line 7, in <module>
    while not r.selection_get(selection = "CLIPBOARD"):
  File "I:\python27\lib\lib-tk\Tkinter.py", line 626, in selection_get
    return self.tk.call(('selection', 'get') + self._options(kw))
_tkinter.TclError: CLIPBOARD selection doesn't exist or form "STRING" not defined

The code:

#based on http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python
from Tkinter import Tk
from time import sleep
r = Tk()
r.withdraw()

while not r.selection_get(selection = "CLIPBOARD"):
    sleep(0.1)

result = r.selection_get(selection = "CLIPBOARD")
r.clipboard_clear()
#r.clipboard_append('This goes to clipboard')
r.destroy()

print(result)
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.