Skip to content

Instantly share code, notes, and snippets.

@bukowa
Last active November 14, 2019 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bukowa/db2132a1b93c372735221f5d5ca307fa to your computer and use it in GitHub Desktop.
Save bukowa/db2132a1b93c372735221f5d5ca307fa to your computer and use it in GitHub Desktop.
clipboard > windows > python >: read_clipboard_data()
import ctypes
import time
from typing import Any
TABLE = {
'to_list': lambda txt: txt.decode('utf-8').splitlines(),
}
__doc__ = """
Convert data from clipboard into desired format.
PyDev console: starting.
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
>>> from clipboardscript import read_clipboard_data
>>>
>>> data = read_clipboard_data('to_list')
>>> data
['import ctypes', 'import time', 'from typing import Any']
"""
# SOURCE https://stackoverflow.com/a/23285159
CF_TEXT = 1
kernel32 = ctypes.windll.kernel32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32 = ctypes.windll.user32
user32.GetClipboardData.restype = ctypes.c_void_p
def get_clipboard_text():
user32.OpenClipboard(0)
try:
if user32.IsClipboardFormatAvailable(CF_TEXT):
data = user32.GetClipboardData(CF_TEXT)
data_locked = kernel32.GlobalLock(data)
text = ctypes.c_char_p(data_locked)
value = text.value
kernel32.GlobalUnlock(data_locked)
return value
finally:
user32.CloseClipboard()
# ENDSOURCE
class BasicException(Exception): pass
class FormattingNotFoundException(BasicException): pass
def read_clipboard_data(formatting, table=None) -> Any:
table = table or TABLE
while True:
clipboard_text = get_clipboard_text()
formatting_func = table.get(formatting, None)
if not formatting_func:
raise FormattingNotFoundException('Using table:', table)
txt = formatting_func(clipboard_text)
return txt
if __name__ == '__main__':
read_clipboard_data('to_list')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment