- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
Hi Folks,
I want to copy data from python to my windows clipboard, to be able to paste in a text editor.
I would prefer to not have to introduce yet another package the environment though.
I found this code using ctypes on this SO page: https://stackoverflow.com/a/27291478/8886135
#https://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python import ctypes OpenClipboard = ctypes.windll.user32.OpenClipboard EmptyClipboard = ctypes.windll.user32.EmptyClipboard GetClipboardData = ctypes.windll.user32.GetClipboardData SetClipboardData = ctypes.windll.user32.SetClipboardData CloseClipboard = ctypes.windll.user32.CloseClipboard CF_UNICODETEXT = 13 GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc GlobalLock = ctypes.windll.kernel32.GlobalLock GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock GlobalSize = ctypes.windll.kernel32.GlobalSize GMEM_MOVEABLE = 0x0002 GMEM_ZEROINIT = 0x0040 unicode_type = type(u'') def get(): text = None OpenClipboard(None) handle = GetClipboardData(CF_UNICODETEXT) pcontents = GlobalLock(handle) size = GlobalSize(handle) if pcontents and size: raw_data = ctypes.create_string_buffer(size) ctypes.memmove(raw_data, pcontents, size) text = raw_data.raw.decode('utf-16le').rstrip(u'\0') GlobalUnlock(handle) CloseClipboard() return text def put(s): if not isinstance(s, unicode_type): s = s.decode('mbcs') data = s.encode('utf-16le') OpenClipboard(None) EmptyClipboard() handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2) pcontents = GlobalLock(handle) ctypes.memmove(pcontents, data, len(data)) GlobalUnlock(handle) SetClipboardData(CF_UNICODETEXT, handle) CloseClipboard() put(u'test data')
The put() function works in standalone python 2.7, however it is broken when run in Maya.
Error: WindowsError: file <maya console> line xx: exception: access violation writing 0x0000000000000000
I've narrowed it down to this line:
pcontents = GlobalLock(handle)
According to the windows documentation, GlobalLock() should return a pointer to a section of memory that you can copy the python data into. In Maya this always returns 0. This causes an access violation when trying to copy over the data buffer from python.
Is there a workaround for this issue? Is there perhaps a different approach that could be used? All other answers involve installing a dependency or dabbling in subprocess, which I'd rather avoid if I can.
For those interested in a repro, here are the steps:
- Be on Windows 10, Version 1903
- Be on Maya 2018.2
- Copy the code above into Maya Script Editor
- Run the script
- You should get the access violation error
I've also seen that someone has had a similar problem before, but no answer: https://forums.autodesk.com/t5/maya-programming/changes-in-using-ctypes-python-for-maya-2014-2015/m-...
Solved! Go to Solution.