Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Sao chép và dán vào clipboard với module pyperclip trong Python

Giới thiệu

pyperclip copy/paste nội dung vào clipboard. Cross-platform, hỗ trợ Python 2 và 3. Hữu ích khi muốn paste output ra file/phần mềm khác.

Cài đặt

pip install pyperclip
import pyperclip

Copy text vào clipboard

import pyperclip
pyperclip.copy("Hello world!")

Paste text từ clipboard

import pyperclip
text = pyperclip.paste()
print(text)
Hello world!

Paste sau khi copy nội dung mới

Dùng pyperclip.waitForNewPaste() chờ nội dung mới khác hẳn.

import pyperclip
pyperclip.copy("Hello world!")
text = pyperclip.paste()
print(text)
pyperclip.copy('Hello world!')
text = pyperclip.waitForNewPaste()
print(text)
Hello world!
Random message copied

Lưu ý: chương trình kết thúc sau khi in nội dung mới. Nội dung mới phải khác "Hello world!". Nếu muốn paste dù trùng lặp, dùng waitForPaste().

Dữ liệu clipboard luôn là kiểu String.

Kết luận

Đã biết copy/paste clipboard cho automation (build table, v.v.). Cross-platform: Linux, macOS, Windows.