Search code examples
pythonwindowsclipboard

Troubles with clipboard in Python


I'm learning Python right now and I want to write some script that will helps me with work. The idea is: while True: read some string from clipboard, modify it then return it into the clipboard then sleep. So I can paste modified data to anywhere.

Now I'm stuck in using win32clipboard module. I'm using this code:

import win32clipboard

def openClipboard():
    win32clipboard.OpenClipboard()

def closeClipboard():
    try:
        win32clipboard.CloseClipboard()
    except Exception as e:
        print(e)

def getClipboardData():
    if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT):
        return win32clipboard.GetClipboardData()
    else:
        return None

def setClipboardData(data):
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(win32clipboard.CF_TEXT, data)

#assume that I copied '000'

openClipboard()
data = getClipboardData()
print(data) //output: 000, so it's ok
closeClipboard()

openClipboard()
win32clipboard.EmptyClipboard()
setClipboardData(data + '123')
closeClipboard()

openClipboard()
data = getClipboardData()
print(data) //output: 0 0 0 1 2 3, but wtf? o_0
closeClipboard()

I can't understand why there are spaces in the second output?


Solution

  • ralu, thanks. I've got it at the same time I've got your answer. I should've use win32clipboard.SetClipboardText(data) instead of win32clipboard.SetClipboardData(win32clipboard.CF_TEXT, data).