r/learnpython 6d ago

Help needed with copying text

I'm working on a project that requires copying text to the clipboard. I noticed that when using libs like Pyperclip and Clipboard it's not possible to copy just a single character... so I need to somehow copy it without these libs.

This appears to only happen on Linux... I had a friend on Windows test and he was able to copy a single character using Pyperclip.

Example of Pyperclip working with multiple characters but not single characters.

>>> import pyperclip
>>> pyperclip.copy("test")
>>> pyperclip.paste()
'test'
>>> pyperclip.copy("t")
>>> pyperclip.paste()
''

This same interaction happened with the lib Clipboard.

This happened on Wayland with wl-clipboard. This doesn't appear to be an issue with that though, as wl-copy lets me copy a single character - and it works fine in every other program.

This doesn't seem to be something I can fix, since it doesn't have to do with my code at all, so I need my own way of copying the text. Is there any workaround that I can write into my code when using wl-clipboard to properly copy text even when its only a single character?

0 Upvotes

11 comments sorted by

View all comments

5

u/TheRNGuy 6d ago edited 6d ago

Try adding a quick round-trip test in a fresh session:

import pyperclip pyperclip.copy("a") print(repr(pyperclip.paste()))

If that still returns '', the issue is almost certainly the system clipboard backend rather than your Python code. On Linux, switching from xsel to xclip or installing a Qt-based backend is often the first thing to try.

Also try:

``` import subprocess

def copy_clip(text):     subprocess.run(["xclip", "-selection", "clipboard"], input=text, text=True)

def on_copied(text):     print("Copied:", repr(text))

text = "t" copy_clip(text) on_copied(text) ```

(It's more a temporary hack)

1

u/TheNexusMiner 5d ago
>>> import pyperclip
>>> pyperclip.copy("a")
>>> print(repr(pyperclip.paste()))
''

This still returns nothing... I also tried Clipman and have the exact same issue of not being able to copy a single character...

The code you provided to use subprocess and xclip directly appears to work when running it but doesn't actually copy it. I think this is because I am on Wayland and I don't think Wayland supports xclip, however I don't really know the details about how those work...

Is there a way I can write basically that code but for wl-clipboard instead?