DEV Community

Audrey Kadjar
Audrey Kadjar

Posted on

πŸ“‹ πŸ“ Manage your clipboard in the CLI with Python

As someone who frequently copies and pastes content, I've often wondered about the inner workings of the clipboard and whether it was possible to manage it programmatically. I ended up writing a simple Python script that allows you to get the current value in the clipboard, clear it, and get its history via the command line interface (CLI).


How it Works

Here is a step-by-step guide to implementing this functionality:

  • Define a ClipboardManager class: The first step is to define a ClipboardManager class. This class will serve as the foundation for managing clipboard operations within the script. The __init__ method is the constructor: it sets up the initial state of the object when it is created. In this example, __init__ initializes history as an empty list and current_value as None.
   class ClipboardManager:
       def __init__(self):
           self.history = []
           self.current_value = None
Enter fullscreen mode Exit fullscreen mode
  • Implement get clipboard and clear clipboard methods: Using the pyperclip module, we define methods within the ClipboardManager class to interact with the clipboard. These methods allow fetching the current clipboard value and clearing the clipboard. Every time we get the current clipboard value, we add it in the history list to keep track of it.
       def get_clipboard(self):
        value = pyperclip.paste()
        if value != self.current_value:
            self.history.append(value)
            self.current_value = value
        return value

        def clear_clipboard(self):
        pyperclip.copy('')
        self.current_value = ''
        print("Clipboard cleared.")
Enter fullscreen mode Exit fullscreen mode
  • Implement the show history method: Next, we need to include a method that displays the history of clipboard values stored in self.history. In this method, we loop through the items in the list and use the enumerate built-in function to pair each value with an index, producing a numbered list. We set the starting index to 1 to make the output more user-friendly, aligning with the human convention of counting from 1, unlike computers which typically start counting from 0.
    def show_history(self):
        if self.history:
            for idx, value in enumerate(self.history, start=1):
                print(f"{idx}: {value}")
        else:
            print("No history available.")
Enter fullscreen mode Exit fullscreen mode
  • Instantiate the class and provide options in the CLI: The last step is to implement the main execution logic of the script. We instantiate an object of ClipboardManager and create a user-friendly menu in the command-line interface to allow users to perform operations on the clipboard.
    if __name__ == "__main__":
    manager = ClipboardManager()

    while True:
        print("\nMenu:")
        print("1. Get current clipboard value")
        print("2. Show clipboard history")
        print("3. Clear clipboard")
        print("4. Exit")

        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            current_value = manager.get_clipboard()
            print(f"Current clipboard value: {current_value}")

        elif choice == '2':
            manager.show_history()

        elif choice == '3':
            manager.clear_clipboard()

        elif choice == '4':
            print("Exiting...")
            break

        else:
            print("Invalid choice. Please enter a number from 1 to 4.")
Enter fullscreen mode Exit fullscreen mode

This is the final script:

import pyperclip

class ClipboardManager:
    def __init__(self):
        self.history = []
        self.current_value = None

    def get_clipboard(self):
        value = pyperclip.paste()
        if value != self.current_value:
            self.history.append(value)
            self.current_value = value
        return value

    def show_history(self):
        if self.history:
            for idx, value in enumerate(self.history, start=1):
                print(f"{idx}: {value}")
        else:
            print("No history available.")

    def clear_clipboard(self):
        pyperclip.copy('')
        self.current_value = ''
        print("Clipboard cleared.")

if __name__ == "__main__":
    manager = ClipboardManager()

    while True:
        print("\nMenu:")
        print("1. Get current clipboard value")
        print("2. Show clipboard history")
        print("3. Clear clipboard")
        print("4. Exit")

        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            current_value = manager.get_clipboard()
            print(f"Current clipboard value: {current_value}")

        elif choice == '2':
            manager.show_history()

        elif choice == '3':
            manager.clear_clipboard()

        elif choice == '4':
            print("Exiting...")
            break

        else:
            print("Invalid choice. Please enter a number from 1 to 4.")
Enter fullscreen mode Exit fullscreen mode

Usage

To utilize this script, follow these steps:

  • Save the script into a file with a .py extension (e.g., clipboard-script.py).

  • Open a terminal and navigate to the directory containing the script.

  • Run the script by providing the script path. For example:

python3 <script-path>
Enter fullscreen mode Exit fullscreen mode
python3 clipboard-script.py
Enter fullscreen mode Exit fullscreen mode

Now, you can test the script by copying text from your command-line interface (CLI) and begin utilizing its functionality to manage clipboard operations effectively.✨

Feel free to reach out if you have any questions! You can also find me on Github, LinkedIn, and Instagram.

Top comments (0)