
python中可以使用ctypes库来操作剪切板:
1、调用get_clipboard() 获取剪切板数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | if __name__ == '__main__' :
# 获取剪切板内字符串
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 ( '剪切板为空。' )
剪切板为空时,输出结果为:
None < class 'NoneType' >
剪切板为空。
复制一个字符串后运行上面的测试代码(在这里我复制了 python ),输出结果为:
b 'Python' < class 'bytes' >
Python < class 'str' >
|
剪切板中无数据时,get_clipboard() 返回 None。
当剪切板中有数据时,get_clipboard() 将其以 bytes 格式返回;
使用 text_str = text_raw.decode('utf_8')将 bytes 转化为 str。
2、调用 empty_clipboard() 清空剪切板
1 2 3 4 5 | if __name__ == '__main__' :
# 清空剪切板
empty_clipboard()
text = get_clipboard()
print (text)复制一个字符串后运行代码,输出结果为:None
|
3、调用 set_clipboard() 写入剪切板
1 2 3 4 5 6 7 8 | if __name__ == '__main__' :
# 向剪切板内写入 ascii 字符串
set_clipboard( 'py!' )
text = get_clipboard()
print (text)
输出结果为:
b 'py!'
|
更多Python知识请关注Python自学网。