Pyperclip is a python module that enables managing our system clipboard. It is a cross-platform module.
To The Point
Installation of pyperclip
System Dependency
On Windows you don't need to install any additional software.
On Linux you need to install either xclip
or xsel
, but the recommended is xclip
:
sudo apt-get install xclip
Installation
Python module can be installed with simple pip command :
pip install pyperclip
Or via pipenv :
pipenv install pyperclip
Using pyperclip
That's pretty easy, commands are :
-
pyperclip.copy
- for making a copy of data to clipboard (as a parameter) -
pyperclip.paste
- for pasting from clipboard data in python.
Examples of usage
I'm going to use pyperclip as a system for copying summaries from blog-posts.
Check out this script that I'm going to use to make my day-to-day easier and more automated:
import pyperclip
import argparse
YOUR_DOMAIN = "http://witkowskibartosz.com/blog/"
def get_summary(post_file_markdown):
SLUG_TAG = "Slug: "
SUMMARY_TAG = "Summary: "
summary = ""
slug = ""
with open(post_file_markdown, 'r') as filemarkdown:
for line in filemarkdown.read().split("\n"):
if SLUG_TAG in line:
slug = line.split(SLUG_TAG)[1]
if SUMMARY_TAG in line:
summary = line.split(SUMMARY_TAG)[1]
return (slug, summary)
def make_social_text_and_copy(slug, summary):
text = summary + " : "+ YOUR_DOMAIN + slug + ".html"
pyperclip.copy(text)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Arguments of this script')
parser.add_argument('markdownfile', metavar='N', type=str, nargs='+')
args = parser.parse_args()
data = get_summary(args.markdownfile[0])
make_social_text_and_copy(*data)
This basically reads md file, looks for SLUG and SUMMARY and makes a social text that is being copied to clipboard.
To use this script, you need to add path to md file as argument to python script like that:
pipenv run python get_post_summary.py ~/your_path_to_md_file.md
Snippets
Simulates CTRL+C (copy):
pyperclip.copy('some text that goes to clipboard')
Simulates CTRL+V (paste):
pyperclip.paste()
Acknowledgements
Auto-promotion
Related links
- GitHub - asweigart/pyperclip: Python module for cross-platform clipboard functions.
- 16.4. argparse — Parser for command-line options, arguments and sub-commands — Python 3.3.7 documentation
Thanks!
That's it :) Comment, share or don't - up to you.
Any suggestions what I should blog about? Post me a comment in the box below or poke me at Twitter: @anselmos88.
See you in the next episode! Cheers!
Comments
comments powered by Disqus