Last Updated on 2021-12-28 by Clay
If you want to write a simple script with Python, to access the system clipboard to set or get a text, how do we do? Actually, we can use the built-in Python module subprocess to do it.
What is the system clipboard?
The system clipboard is a very convenient tool that allows users to exchange information by copying and pasting on different software and web pages. It can be said the be the most inseparable computer for modern people.
Of course, in addition to text can be copied and pasted, we can also access pictures. However, in this article, for the sake of simple and clear examples, only the text content is deal with.
Example
Different operating systems support different clipboard processing packages. In Linux, we can use xclip to access the system clipboard.
The following is the xclip parameter description.
-selection
: Since there are multiple clipboards in the system, we need to select the clipboard to be used. (By the way, do not use outdated Cut Buffers)
-o
: Read from selected clipboard
Linux version
# coding: utf-8
import subprocess
def get_clipboard_data():
p = subprocess.Popen(["xclip", "-selection", "clipboard", "-o"], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
def set_clipboard_data(data):
data = bytes(data, "utf-8")
p = subprocess.Popen(["xclip", "-selection", "clipboard"], stdin=subprocess.PIPE)
p.stdin.write(data)
p.stdin.close()
retcode = p.wait()
if __name__ == "__main__":
# our string data
data = "Today is a nice day!"
# Set the data
set_clipboard_data(data)
# Get the new data
new_data = get_clipboard_data()
# Print it out
print(new_data)
Output:
b'This is a nice day!'
Mac OS version
# coding: utf-8
import subprocess
def get_clipboard_data():
p = subprocess.Popen(["pbpaste"], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
def set_clipboard_data(data):
data = bytes(data, "utf-8")
p = subprocess.Popen(["pbcopy"], stdin=subprocess.PIPE)
p.stdin.write(data)
p.stdin.close()
retcode = p.wait()
if __name__ == "__main__":
# our string data
data = "Today is a nice day!"
# Set the data
set_clipboard_data(data)
# Get the new data
new_data = get_clipboard_data()
# Print it out
print(new_data)
Output:
b'This is a nice day!'