Skip to content

# Clipboard Integration

Nearly every operating system has some notion of a short-term storage area which can be accessed by any program. Usually this is called the clipboard, but sometimes people refer to it as the paste buffer.

`cmd2` integrates with the operating system clipboard using the pyperclip module. Command output can be sent to the clipboard by ending the command with a greater than symbol:

    mycommand args >

Think of it as redirecting the output to an unnamed, ephemeral place: the clipboard. You can also append output to the current contents of the clipboard by ending the command with two greater than symbols:

    mycommand arg1 arg2 >>

Limitation

The ability to redirect command output only works directly from a `cmd2` command. It doesn't work after piping output to a shell command.

## Developers

You can control whether the above user features of adding output to the operating system clipboard are allowed for the user by setting the cmd2.Cmd.allow_clipboard attribute. The default value is `True`. Set it to `False` and the above functionality will generate an error message instead of adding the output to the clipboard. cmd2.Cmd.allow_clipboard can be set upon initialization, and you can change it at any time from within your code.

If you would like your `cmd2` based application to be able to use the clipboard in additional or alternative ways, you can use the following methods (which work uniformly on Windows, macOS, and Linux).

## `` cmd2.clipboard

Module provides basic ability to copy from and paste to the clipboard/pastebuffer.

### `` get_paste_buffer

    get_paste_buffer()

Get the contents of the clipboard / paste buffer.

RETURNS | DESCRIPTION
--- | ---
`str` | contents of the clipboard

Source code in `cmd2/clipboard.py`

     8
     9
    10
    11
    12
    13

    def get_paste_buffer() -> str:
        """Get the contents of the clipboard / paste buffer.

        :return: contents of the clipboard
        """
        return typing.cast(str, pyperclip.paste())

### `` write_to_paste_buffer

    write_to_paste_buffer(txt)

Copy text to the clipboard / paste buffer.

PARAMETER | DESCRIPTION
--- | ---
`txt` | text to copy to the clipboard TYPE: `str`

Source code in `cmd2/clipboard.py`

    16
    17
    18
    19
    20
    21

    def write_to_paste_buffer(txt: str) -> None:
        """Copy text to the clipboard / paste buffer.

        :param txt: text to copy to the clipboard
        """
        pyperclip.copy(txt)