copying and pasting from/to clipboard with python/win32
Asked Answered
C

4

5

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?

Cyder answered 30/9, 2010 at 3:35 Comment(0)
M
8

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

Mccullum answered 30/9, 2010 at 3:59 Comment(0)
B
3

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/

Brassy answered 18/6, 2012 at 21:35 Comment(0)
I
1

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?

Imperial answered 7/11, 2011 at 16:25 Comment(1)
is it possible to send back the data as CF_HTML using Tkinter?Karlynkarma
N
0

Copy some file paths to the clipboard using powershell (easy code)

from subprocess import check_output, CREATE_NO_WINDOW

path_1 = "C:\\temp\\000001.jpg"
path_2 = "C:\\temp\\000003.jpg"
output = check_output(
        f"""powershell "Set-Clipboard -LiteralPath '{path_1 }', '{path_2 }'" """,
        shell=False,
        creationflags=CREATE_NO_WINDOW
).decode('cp850')
print(output )

Paste the filenames using win32clipboard (faster)

import win32clipboard
win32clipboard.OpenClipboard()
if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_HDROP):
    filenames = win32clipboard.GetClipboardData(win32clipboard.CF_HDROP)
win32clipboard.CloseClipboard()
for filename in filenames:
    print(filename)
Nagging answered 10/7, 2023 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.