有時(shí)候?qū)懩_本的時(shí)候會(huì)有操作系統(tǒng)剪切板的需求,就是
- 獲取剪切板中的字符串
- 清空剪切板
- 向剪切板中寫入字符串
方法包括使用 tkinter , ctypes 這兩個(gè) python 標(biāo)準(zhǔn)庫钠绍, 或者安裝 Qt 等第三方庫來操作剪切板观蓄。
ctypes 操作剪切板
先寫 windows 系統(tǒng)下 ctypes 庫如何操作剪切板吧。ctypes 這個(gè)庫主要用于調(diào)用動(dòng)態(tài)鏈接函數(shù)或共享庫色迂,使用起來比較難。
于是我在 gist 上找了一段代碼巧号,是面向?qū)ο蟮膶懛ㄅǖ桑€有一兩處不兼容 python3 。略作修改后放在簡(jiǎn)書上女轿,也許能方便有需求的人箭启。雖然我看不太懂這段代碼,但好在調(diào)用起來還挺簡(jiǎn)單的蛉迹,后面會(huì)有簡(jiǎn)單的調(diào)用示例傅寡。
'''
操作剪切板:讀取剪切板的字符串;清空剪切板;向剪切板中寫入字符串(只能寫入 ascii 字符)。
win10, python3,
'''
from ctypes import *
user32 = windll.user32
kernel32 = windll.kernel32
def get_clipboard():
user32.OpenClipboard(c_int(0))
contents = c_char_p(user32.GetClipboardData(c_int(1))).value
user32.CloseClipboard()
return contents
def empty_clipboard():
user32.OpenClipboard(c_int(0))
user32.EmptyClipboard()
user32.CloseClipboard()
def set_clipboard(data):
user32.OpenClipboard(c_int(0))
user32.EmptyClipboard()
alloc = kernel32.GlobalAlloc(0x2000, len(bytes(data, encoding='utf_8'))+1)
# alloc = kernel32.GlobalAlloc(0x2000, len(data)+1)
lock = kernel32.GlobalLock(alloc)
cdll.msvcrt.strcpy(c_char_p(lock),bytes(data, encoding='utf_8'))
# cdll.msvcrt.strcpy(c_char_p(lock), data)
kernel32.GlobalUnlock(alloc)
user32.SetClipboardData(c_int(1),alloc)
user32.CloseClipboard()
調(diào)用 get_clipboard() 獲取剪切板數(shù)據(jù)
if __name__ == '__main__':
# 獲取剪切板內(nèi)字符串
text_raw = get_clipboard()
print('{0} {1}'.format(text_raw, type(text_raw)))
try:
text_str = text_raw.decode('utf_8')
print('{0} {1}'.format(text_str, type(text_str)))
except:
print('剪切板為空北救。')
剪切板為空時(shí)荐操,輸出結(jié)果為:
None <class 'NoneType'>
剪切板為空。
復(fù)制一個(gè)字符串后運(yùn)行上面的測(cè)試代碼(在這里我復(fù)制了 python )珍策,輸出結(jié)果為:
b'Python' <class 'bytes'>
Python <class 'str'>
剪切板中無數(shù)據(jù)時(shí)托启,get_clipboard() 返回 None。
當(dāng)剪切板中有數(shù)據(jù)時(shí)攘宙,get_clipboard() 將其以 bytes 格式返回屯耸;
使用 text_str = text_raw.decode('utf_8')
將 bytes 轉(zhuǎn)化為 str。
調(diào)用 empty_clipboard() 清空剪切板
if __name__ == '__main__':
# 清空剪切板
empty_clipboard()
text = get_clipboard()
print(text)
復(fù)制一個(gè)字符串后運(yùn)行代碼蹭劈,輸出結(jié)果為:
None
調(diào)用 set_clipboard() 寫入剪切板
if __name__ == '__main__':
# 向剪切板內(nèi)寫入 ascii 字符串
set_clipboard('py!')
text = get_clipboard()
print(text)
輸出結(jié)果為:
b'py!'
相關(guān)
完整代碼在 github 上疗绣。
如果這篇文章有任何錯(cuò)誤或不適當(dāng)?shù)牡胤剑?qǐng)?jiān)谠u(píng)論里指出铺韧《喟或者你有更好的方法,也請(qǐng)寫在評(píng)論里祟蚀,感謝工窍!