I would like a user to select text on a webpage, and to capture that text as a string automatically using the least number of user inputs as possible. Ideally, the user would simply select the desired text using ctrl-c, immediately after I would run the GetClipboardData() function and obtain that text. I have a solution that is close at this point, but it requires the user to hit enter:

import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.CloseClipboard()
**string = input("select text and hit enter")**
win32clipboard.OpenClipboard()
win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return string

Ideally, upon hitting ctrl-c, I would run GetClipboardData() without the user having to press enter. Any ideas?

You have return out of function at line 9, and extra ** at line 4 as bold is not allowed in code.

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()


set_text('')
while not (get_text()):
    sleep(0.1)

print(get_text())

You can also use the PyQT or PySide GUI toolkit ...

# test PySide widgets
# copy text to and from the clipboard
# tested with PySide474 and Python27 or Python32

from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication([])

# ----- start your widget test code ----

clipboard = app.clipboard()

clipboard.setText("the clipboard text")

text = clipboard.text()
print(text)

# ---- end of widget test code -----

# for this case ...
app.processEvents()
#app.exec_()
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.