Skip to content

Instantly share code, notes, and snippets.

@XuankangLin
Created January 28, 2017 04:20
Show Gist options
  • Save XuankangLin/7ec82f80a0044a52330720244de2d15a to your computer and use it in GitHub Desktop.
Save XuankangLin/7ec82f80a0044a52330720244de2d15a to your computer and use it in GitHub Desktop.
Read from and Write to clipboards in python scripts, works on Mac at least.
import subprocess
def getClipboardData():
p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
def setClipboardData(data):
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
p.stdin.write(data)
p.stdin.close()
retcode = p.wait()
@acsr
Copy link

acsr commented May 24, 2023

A prefix like b"text" for a string or proper encoded bytes conversion is required before entering data to setClipboardData(data) as argument to avoid:

TypeError: a bytes-like object is required, not 'str'

To transform a unicode string to a byte string in Python do this:

'foo'.encode('utf_8')
# result is bytes string
b'foo'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment