Search code examples
pythonwindowspywin32win32com

Python win32clipboard recursive call not working as expected (but actually better)


I made this code

import win32clipboard as cb # Used to get the windows clipboard content

def getText():
    errorMsg = '''No text has been copied to the clipboard.
    Copy text to the clipboard and press ENTER:'''

    # The text is in the clipboard
    cb.OpenClipboard()
    text = cb.GetClipboardData()
    cb.CloseClipboard()

    if text == errorMsg:
        raw_input(errorMsg)        
        text = getText() # Recursive call

    cb.OpenClipboard()
    cb.SetClipboardText(errorMsg)
    cb.CloseClipboard()
    return text

If I copy "Hello world" to the clipboard and call the getText() twice I get:

>>> print getText()
Hello world
>>> print getText()
No text has been copied to the clipboard.
Copy text to the clipboard and press OK: [Copied "Hello" and pressed ENTER]
Hello

Now if I try to CTRL-V (paste) into another text editor I get "Hello" - which is amazing, but not what I expected. I expected to have the errorMsg in my clipboard. Keeping the "hello" in the clipboard and call getText() again still prompts the user to copy content to the clipboard.

I don't want to change the behavior of the code, but would like to understand it


Solution

  • Note that the code you've given won't run as is. I believe the line:

    if ocrText == errorMsg:
    

    should actually be:

    if text == errorMsg:
    

    Additionally when you write to the clipboard you should do this:

    cb.OpenClipboard()
    cb.EmptyClipboard()
    cb.SetClipboardText(errorMsg)
    cb.CloseClipboard()
    

    I.e., you need to call EmptyClipboard before setting clipboard data. When I make these changes, it appears to be working as you described, the error message is in the clipboard.