-1

I need a little script which put the content of the clipboard in a variable and then "do things" (i.e. execute other functions with the variable as parameter). The script has to do it every time the clipboard is modified.

Right now I have:

def get_clipboard():
    root = Tk()
    root.withdraw()
    try:
        return root.clipboard_get()
    except:
        return ""

if __name__ == '__main__':
    cb = ""
    while True:
        cb_new = get_clipboard()
        if cb_new == cb or cb_new == "":
            continue
        cb = cb_new
        print(cb) # Here I will call other functions
        print("---------------------------------------------")
        time.sleep(0.1)

But I have an error after some time: unable to realloc 28675 bytes. I guess it is because of the while loop, but I don't know how to do it differently. I tried to use mainloop, but I don't understand how it work and if it is what I need.

Shan-x
  • 1,146
  • 6
  • 19
  • 44
  • 2
    May I ask where you've copied that `get_clipboard` function from so I can give it a downvote? It leaks memory. – Aran-Fey Aug 23 '17 at 08:02
  • @Rawing, maybe [this](https://stackoverflow.com/a/16189232/6634373) one. – CommonSense Aug 23 '17 at 08:30
  • That's the one. And as I don't know tkinter at all, I didn't see the problem. – Shan-x Aug 23 '17 at 08:35
  • Every time `get_clipboard()` is called, you are creating a _new_ invisible window. You never destroy this window. It won't take long before you have hundreds or thousands of these invisible windows, each one taking up some memory. – Bryan Oakley Aug 23 '17 at 11:50

1 Answers1

1

The get_clipboard function creates a tkinter window but never properly destroys it. Doing this in a loop, 10 times per second, accumulates memory until there isn't enough left to create another window and your script crashes.

Change the function to this:

def get_clipboard():
    root = Tk()
    root.withdraw()
    try:
        return root.clipboard_get()
    except:
        return ""
    finally:
        root.destroy()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Arguably even better would be to create the root window once at the start of the program, instead of continually creating and destroying it. – Bryan Oakley Aug 23 '17 at 11:52