Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Copy และ Paste ไปยัง Clipboard ด้วย Pyperclip ใน Python

บทนำ

pyperclip คัดลอก/วางข้อความไปยัง clipboard ทำงาน cross-platform (Windows, macOS, Linux) รองรับ Python 2 และ 3

การติดตั้ง

pip install pyperclip

การใช้งาน

Copy

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

Paste

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

Wait for New Paste

pyperclip.copy('Hello world!')
text = pyperclip.waitForNewPaste()  # รอจนกว่าจะมีการ copy ใหม่ (ต่างจากเดิม)
print(text)

มี waitForPaste() ที่รอ paste แม้ข้อความเดิมก็ตาม

ข้อสังเกต

  • ข้อมูลใน clipboard เสมอเป็น string
  • เหมาะสำหรับ automation: copy/paste ซ้ำๆ, สร้างตาราง, fill forms

สรุป

pyperclip ทำให้ควบคุม clipboard ได้ง่าย ใช้ใน automation tools, testing, productivity scripts