简体   繁体   中英

Can python send text to the Mac clipboard

I'd like my python program to place some text in the Mac clipboard.

Is this possible?

How to write a Unicode string to the Mac clipboard:

import subprocess

def write_to_clipboard(output):
    process = subprocess.Popen(
        'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
    process.communicate(output.encode('utf-8'))

How to read a Unicode string from the Mac clipboard:

import subprocess

def read_from_clipboard():
    return subprocess.check_output(
        'pbpaste', env={'LANG': 'en_US.UTF-8'}).decode('utf-8')

Works on both Python 2.7 and Python 3.4.

2021 Update: If you need to be able to read the clipboard on other operating systems and not just Mac and are okay with adding an external library, pyperclip also seems to work well. I tested it on Mac with Unicode text:

python -m pip install pyperclip
python -c 'import pyperclip; pyperclip.copy("私はDavid!🙂")'  # copy
python -c 'import pyperclip; print(repr(pyperclip.paste()))'  # paste

A simple way:

cmd = 'echo %s | tr -d "\n" | pbcopy' % str
os.system(cmd)

A cross-platform way:
https://stackoverflow.com/a/4203897/805627

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()

The following code use PyObjC ( https://pyobjc.readthedocs.io )

from AppKit import NSPasteboard, NSArray

pb = NSPasteboard.generalPasteboard()
pb.clearContents()
a = NSArray.arrayWithObject_("hello world")
pb.writeObjects_(a)

As explained in Cocoa documentation , copying requires three step :

  • get the pasteboard
  • clear it
  • fill it

You fill the pasteboard with an array of object (here a contains only one string).

New answer:

This page suggests:

Implementation for All Mac OS X Versions

The other Mac module (MacSharedClipboard.py, in Listing 4) implements the clipboard interface on top of two command-line programs called pbcopy (which copies text into the clipboard) and pbpaste (which pastes whatever text is in the clipboard). The prefix "pb" stands for "pasteboard," the Mac term for clipboard.

Old answer:

Apparently so:

http://code.activestate.com/recipes/410615/

is a simple script demonstrating how to do it.

Edit: Just realised this relies on Carbon, so might not be ideal... depends a bit what you're using it for.

I know this is an older post, but I have found a very elegant solution to this problem.

There is a library named PyClip , which can be found at https://github.com/georgefs/pyclip-copycat .

The syntax is pretty simple (example from the Github repo):

import clipboard

# copy some text to the clipboard
clipboard.copy('blah blah blah')

# get the text currently held in the clipboard
text = clipboard.paste()

once you've passed clipboard.copy('foo') you can just cmd + v to get the text

如果您只想将文本放入 mac 剪贴板,则可以使用 shell 的 pbcopy 命令。

Based on @David Foster's answer, I implemented a simple script(only works for mac) to decode python dict(actually, it is parsed from a JSON string) to JSON string, because sometimes when debugging, I need to find the mistake(s) in the data(and the data body is very big and complex, which is hard for human to read), then I would paste it in python shell and json.dumps(data) and copy to VS code, prettify the JSON. So, the script below would be very helpful to my works.

alias pyjson_decode_stdout='python3 -c "import sys, json, subprocess; \
    print(json.dumps(eval(subprocess.check_output( \
        \"pbpaste\", env={\"LANG\": \"en_US.UTF-8\"}).decode(\"utf-8\"))))"'
alias pyjson_decode='python3 -c "import json, subprocess; \
    output=json.dumps(eval(subprocess.check_output(\
        \"pbpaste\", env={\"LANG\": \"en_US.UTF-8\"}).decode(\"utf-8\"))).encode(\"utf-8\"); \
    process=subprocess.Popen(\"pbcopy\", env={\"LANG\": \"en_US.UTF-8\"}, stdin=subprocess.PIPE); \
    process.communicate(output)"'

add the script to ~/.zshrc or ~/.bashrc (based on which sh you use) and new a terminal window, the example usage is copy one dict data, eg {'a': 1} and enter pyjson_decode_stdout would print the parsed json based on this dict; Copy and enter pyjson_decode would write this string to pbcopy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM