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

发布于 2024-08-12 19:54:37 字数 53 浏览 4 评论 0原文

我希望我的 python 程序在 Mac 剪贴板中放置一些文本。

这可能吗?

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

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

猫烠⑼条掵仅有一顆心 2024-08-19 19:54:38

如何将 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'))

如何从 Mac 剪贴板读取 Unicode 字符串:

import subprocess

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

适用于 Python 2.7 和 Python 3.4。

2021 更新:如果您需要能够在其他操作系统(而不仅仅是 Mac)上读取剪贴板,并且可以添加外部库,pyperclip 似乎也运行良好。我在 Mac 上用 Unicode 文本测试了它:

python -m pip install pyperclip
python -c 'import pyperclip; pyperclip.copy("私はDavid!

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
摇划花蜜的午后 2024-08-19 19:54:38

一种简单的方法:

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

一种跨平台的方法:
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()

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()
时光暖心i 2024-08-19 19:54:38

以下代码使用 PyObjC (https://pyobjc.readthedocs.io)

from AppKit import NSPasteboard, NSArray

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

作为 在 Cocoa 中解释文档,复制需要三个步骤:

  • 获取粘贴板
  • 清除它
  • 填充它

您用一组对象填充粘贴板(这里 a 仅包含一个字符串)。

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

梦年海沫深 2024-08-19 19:54:38

新答案:

此页面建议:

针对所有 Mac OS X 的实现
版本

其他 Mac 模块
(MacSharedClipboard.py,在清单 4 中)
实现剪贴板接口
两个命令行程序的顶部
称为 pbcopy (它将文本复制到
剪贴板)和 pbpaste(
粘贴中的任何文本
剪贴板)。前缀“pb”代表
“粘贴板”,Mac 术语
剪贴板。

旧答案:

显然是这样:

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

是一个简单的脚本,演示了如何执行此操作。

编辑:刚刚意识到这依赖于 Carbon,所以可能并不理想......取决于你使用它的目的。

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.

原谅过去的我 2024-08-19 19:54:38

我知道这是一篇较旧的文章,但我找到了解决这个问题的一个非常优雅的解决方案。

有一个名为 PyClip 的库,可以在 https://github 找到。 com/georgefs/pyclip-copycat

语法非常简单(来自 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()

一旦传递了 clipboard.copy('foo'),您只需 cmd + v 即可获取文本

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

杯别 2024-08-19 19:54:38

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

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

请帮我爱他 2024-08-19 19:54:38

基于@David Foster的回答,我实现了一个简单的脚本(仅适用于mac)来将python dict(实际上,它是从JSON字符串解析的)解码为JSON字符串,因为有时在调试时,我需要找到错误(s )在数据中(并且数据体非常大且复杂,这对于人类来说很难阅读),然后我将其粘贴到python shell和 json.dumps(data) 并复制到VS代码,美化 JSON。所以,下面的脚本对我的作品非常有帮助。

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

将脚本添加到 ~/.zshrc~/.bashrc (基于您使用的 sh)并新建一个终端窗口,示例用法是复制一份字典数据,例如 {'a': 1} 并输入 pyjson_decode_stdout 将根据该字典打印解析后的 json;复制并输入pyjson_decode会将这个字符串写入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, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文