copying and pasting from/to clipboard with python/win32

11,702

Solution 1

To put data in the clipboard, you want to open the clipboard, then call EmptyClipboard before SetClipboardData.

Solution 2

You can also use the pyperclip.py module to avoid requiring the win32 dependency. It's just a single python module that is cross platform, and for Windows it make DLL calls directly:

http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/

Solution 3

If it's OK to not use win32 you can use Tkinter in the python standard library, as shown here: How do I copy a string to the clipboard on Windows using Python?

Share:
11,702
prosseek
Author by

prosseek

A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence

Updated on June 09, 2022

Comments

  • prosseek
    prosseek almost 2 years

    I downloaded the win32 for python 2.6 from this site.

    This is the code to get/set the clipboard.

    def test():
        OpenClipboard() 
        d=GetClipboardData(win32con.CF_TEXT) # get clipboard data
        SetClipboardData(win32con.CF_TEXT, "Hello") # set clipboard data
        CloseClipboard()
    
    if __name__ == '__main__':
        if sys.platform == 'win32':
            from win32clipboard import *
            import win32gui, win32con
            test()
    

    It works well with GetClipboarData, but SetClipboardData doesn't seem to work, as when I run the test(), I expect to get "hello" with ^V, but something that I copied before.

    What might be wrong?

  • JinSnow
    JinSnow over 7 years
    is it possible to send back the data as CF_HTML using Tkinter?