Copy to clipboard using st;message

Hello everyone,

I’m trying to make a “copy to clipboard” button but it’s not working actually.

I tried to follow the solutions on
Copy to clipboard using st.markdown but I got this error instead:

“PyperclipException: Pyperclip could not find a copy/paste mechanism for your system. For more information, please see Welcome to Pyperclip’s documentation! — Pyperclip 1.5 documentation

I’ve tried installing the necessary packages to make copy/paste possible (xcel, xclip or even PyQT4) but I still get this error, do you have any solution please?

Hi @Zak

There’s a similar functionality that st.code provides, have you given this a try, more info and code snippet in the link below:

1 Like

Hi @dataprofessor, thank you for your answer,

I also tried to use st.code but it seems that it gives you a single-line response, without newlines, and makes the desired response look less aesthetic than st.markdown (even if I use langague = “markdown”), is there any other solution please ?

Hi @Zak

The aesthetic of the returned contents in st.code is a function of the provided input text.

Let’s say that if we provide the text as a single line, then the returned output would be a single line

code = 'def hello(): print("Hello, Streamlit!")'
st.code(code, language='python')

To achieve multi line then we’ll have to format our string to have new lines (\n) and to add tabs we can use \t.

Please consider the following code snippet:

import streamlit as st

code1 = '''def hello():
    print("Hello, Streamlit!")'''

code2 = '''def hello(): print("Hello, Streamlit!")'''

code3 = '''def hello():\n\tprint("Hello, Streamlit!")'''

code4 = '''def hello():\n    print("Hello, Streamlit!")'''

code5 = '''def hello():\n    print("Hello, Streamlit!")'''

which gives the following output:

Hope this helps

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.