Can python send text to the Mac clipboard

Viewed 24221

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

Is this possible?

7 Answers

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.

Related