最近在網(wǎng)上搜索Python調(diào)用剪切板的方法,得到比較多的說法是調(diào)用ctypes包中自帶的函數(shù)get_clipboard和set_clipboard函數(shù),可是但我動手實(shí)現(xiàn)時(shí)卻發(fā)現(xiàn)根本沒有這兩個(gè)函數(shù),于是我覺得自己寫一篇文字講述Python的剪切板,可能不全,敬請諒解。
網(wǎng)上看到有人說pandas包里有從剪切板到數(shù)據(jù)庫的方法read_clipboard,于是通過閱讀內(nèi)部文件,發(fā)現(xiàn)了pandas的內(nèi)部剪切板方法,我個(gè)人認(rèn)為這是最好用的方法:
1. 使用pandas.io.clipboard的方法
安裝有pandas包的小伙伴可以試一試,安裝代碼:Win+R輸入pip install pandas
import pandas.io.clipboard as cb
cb.copy("復(fù)制內(nèi)容") # 復(fù)制到剪切板
print(cb.paste()) # 從剪切板粘貼(獲取內(nèi)容),并打印
2. 使用pyperclip的方法
安裝有pyperclip包的小伙伴可以試一試,安裝代碼:Win+R輸入pip install?pyperclip
import pyperclip as cb
cb.copy("復(fù)制內(nèi)容") # 復(fù)制到剪切板
print(cb.paste()) # 從剪切板粘貼(獲取內(nèi)容),并打印
參考文章:python如何操作剪切板? | w3c筆記
3. 使用win32clipboard的方法
安裝有win32clipboard?包的小伙伴可以試一試,安裝代碼:Win+R輸入pip install?win32clipboard
import win32clipboard as cb
cb.OpenClipboard() # 打開剪切板
cb.SetClipboardData(1, "復(fù)制內(nèi)容") # 復(fù)制到剪切板
print(cb.GetClipboardData(1)) # 從剪切板粘貼(獲取內(nèi)容),并打印
cb.CloseClipboard() # 關(guān)閉剪切板
參考文章:Python使用剪切板的方法(python 操作剪切板)-python教程-知優(yōu)網(wǎng)
4. 使用os.system控制命令的方法
如果你用的Windows設(shè)備可以試一試,但這種方法只能復(fù)制,且末尾會多一個(gè)換行:
import os
os.system("echo 復(fù)制內(nèi)容 | clip") # 復(fù)制不含空格的文本到剪切板
# os.system("clip < 文件路徑") # 復(fù)制文件到剪切板
參考文章:【Python & Other】一網(wǎng)打盡 Python復(fù)制文本&文件到剪切板_是小菜欸的博客-CSDN博客_python 復(fù)制到剪貼板
5. 使用subprocess模塊下的Popen方法
如果你用的蘋果電腦或其他Mac設(shè)備可以試一試:文章來源:http://www.zghlxwxcb.cn/news/detail-782381.html
from subprocess import Popen, PIPE
def set_clipboard(data: str): # 復(fù)制到剪切板
with Popen(['pbcopy'], stdin=PIPE) as p:
p.stdin.write(data.encode("utf-8"))
p.stdin.close()
p.communicate()
def get_clipboard(): # 從剪切板粘貼(獲取內(nèi)容)
with Popen(['pbpaste'], stdout=PIPE) as p:
p.wait()
paste_bytes = p.stdout.read()
p.stdout.close()
return paste_bytes.decode('utf-8')
if __name__ == "__main__":
set_clipboard('復(fù)制內(nèi)容') # 復(fù)制到剪切板
print(get_clipboard()) # 從剪切板粘貼(獲取內(nèi)容),并打印
參考文章:Python 操作剪切板 | 操作文章來源地址http://www.zghlxwxcb.cn/news/detail-782381.html
到了這里,關(guān)于Python調(diào)用剪切板的幾種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!