English 中文(简体)
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?

最佳回答

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.

问题回答

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 "
" | 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).

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

if you just wanted to put text into the mac clipboard, you could use the shell s pbcopy command.

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, e.g. { 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.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签