Skip to content

Fix #12529 / Improve to_clipboard for objects containing unicode #12580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.18.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ Performance Improvements

Bug Fixes
~~~~~~~~~

- Bug in ``to_clipboard`` when called for objects containing unicode without passing an encoding (:issue:`12529`)
9 changes: 9 additions & 0 deletions pandas/io/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
- Linux: xclip, or xsel (with gtk or PyQt4 modules)
- Windows:
- OS X:

If the object contains unicode and no encoding is passed as keyword
argument, the default locale will be used.
"""
from pandas.util.clipboard import clipboard_set
if excel is None:
Expand All @@ -86,6 +89,12 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
obj.to_csv(buf, sep=sep, **kwargs)
clipboard_set(buf.getvalue())
return
except UnicodeEncodeError:
# try again with encoding from locale
from locale import getdefaultlocale
obj.to_csv(buf, sep=sep, encoding=getdefaultlocale()[1], **kwargs)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe using default locale is not necessary. utf-8 should do the job (plus decoding buf.getvalue to utf-8) . The windows code of pyperclip (pandas.util.clipboard) would ultimately convert it back to unicode.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a while ago since I looked at this. I just remember that I found some edge cases which still failed. I'll try to find my test cases to see if what you propose works.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I didn't want to submit a new PR while yours is open. But probably more important is whether this works for your edge cases and on your system.

clipboard_set(buf.getvalue())
return
except:
pass

Expand Down