简体   繁体   English

python可以将文本发送到Mac剪贴板吗

[英]Can python send text to the Mac clipboard

I'd like my python program to place some text in the Mac clipboard.我希望我的 python 程序在 Mac 剪贴板中放置一些文本。

Is this possible?这可能吗?

How to write a Unicode string to the Mac clipboard:如何将 Unicode 字符串写入 Mac 剪贴板:

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:如何从 Mac 剪贴板读取 Unicode 字符串:

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.适用于 Python 2.7 和 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. 2021 年更新:如果您需要能够在其他操作系统上读取剪贴板,而不仅仅是 Mac,并且可以添加外部库,那么 pyperclip似乎也运行良好。 I tested it on Mac with Unicode text:我在 Mac 上用 Unicode 文本对其进行了测试:

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 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 )以下代码使用 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 :正如Cocoa 文档中解释的,复制需要三个步骤:

  • get the pasteboard拿到剪贴板
  • clear it清除它
  • fill it填充

You fill the pasteboard with an array of object (here a contains only one string).你用一组对象填充粘贴板(这里a只包含一个字符串)。

New answer:新答案:

This page suggests:此页面建议:

Implementation for All Mac OS X Versions所有 Mac OS X 版本的实现

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).另一个 Mac 模块(MacSharedClipboard.py,在清单 4 中)在两个名为 pbcopy(将文本复制到剪贴板)和 pbpaste(粘贴剪贴板中的任何文本)的命令行程序之上实现剪贴板接口。 The prefix "pb" stands for "pasteboard," the Mac term for clipboard.前缀“pb”代表“粘贴板”,这是剪贴板的 Mac 术语。

Old answer:旧答案:

Apparently so:显然是这样:

http://code.activestate.com/recipes/410615/ 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 .有一个名为PyClip的库,可以在https://github.com/georgefs/pyclip-copycat找到。

The syntax is pretty simple (example from the Github repo):语法非常简单(来自 Github 存储库的示例):

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一旦你通过了clipboard.copy('foo')你就可以cmd + v来获取文本

如果您只想将文本放入 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.基于@David Foster 的回答,我实现了一个简单的脚本(仅适用于 mac)来将 python dict(实际上是从 JSON 字符串解析出来的)解码为 JSON 字符串,因为有时在调试时,我需要找出错误) 中的数据(并且数据体非常大且复杂,人类难以阅读),然后我将其粘贴到 python shell 和json.dumps(data)并复制到 VS 代码,美化 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;将脚本添加到~/.zshrc~/.bashrc (基于您使用的sh )并新建一个终端窗口,示例用法是复制一个 dict 数据,例如{'a': 1}并输入pyjson_decode_stdout将打印根据这个 dict 解析 json; Copy and enter pyjson_decode would write this string to pbcopy .复制并输入pyjson_decode会将这个字符串写入pbcopy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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