Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/pandas/io/clipboards.py
7815 views
1
""" io on the clipboard """
2
from __future__ import annotations
3
4
from io import StringIO
5
import warnings
6
7
from pandas.core.dtypes.generic import ABCDataFrame
8
9
from pandas import (
10
get_option,
11
option_context,
12
)
13
14
15
def read_clipboard(sep: str = r"\s+", **kwargs): # pragma: no cover
16
r"""
17
Read text from clipboard and pass to read_csv.
18
19
Parameters
20
----------
21
sep : str, default '\s+'
22
A string or regex delimiter. The default of '\s+' denotes
23
one or more whitespace characters.
24
25
**kwargs
26
See read_csv for the full argument list.
27
28
Returns
29
-------
30
DataFrame
31
A parsed DataFrame object.
32
"""
33
encoding = kwargs.pop("encoding", "utf-8")
34
35
# only utf-8 is valid for passed value because that's what clipboard
36
# supports
37
if encoding is not None and encoding.lower().replace("-", "") != "utf8":
38
raise NotImplementedError("reading from clipboard only supports utf-8 encoding")
39
40
from pandas.io.clipboard import clipboard_get
41
from pandas.io.parsers import read_csv
42
43
text = clipboard_get()
44
45
# Try to decode (if needed, as "text" might already be a string here).
46
try:
47
text = text.decode(kwargs.get("encoding") or get_option("display.encoding"))
48
except AttributeError:
49
pass
50
51
# Excel copies into clipboard with \t separation
52
# inspect no more then the 10 first lines, if they
53
# all contain an equal number (>0) of tabs, infer
54
# that this came from excel and set 'sep' accordingly
55
lines = text[:10000].split("\n")[:-1][:10]
56
57
# Need to remove leading white space, since read_csv
58
# accepts:
59
# a b
60
# 0 1 2
61
# 1 3 4
62
63
counts = {x.lstrip(" ").count("\t") for x in lines}
64
if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0:
65
sep = "\t"
66
# check the number of leading tabs in the first line
67
# to account for index columns
68
index_length = len(lines[0]) - len(lines[0].lstrip(" \t"))
69
if index_length != 0:
70
kwargs.setdefault("index_col", list(range(index_length)))
71
72
# Edge case where sep is specified to be None, return to default
73
if sep is None and kwargs.get("delim_whitespace") is None:
74
sep = r"\s+"
75
76
# Regex separator currently only works with python engine.
77
# Default to python if separator is multi-character (regex)
78
if len(sep) > 1 and kwargs.get("engine") is None:
79
kwargs["engine"] = "python"
80
elif len(sep) > 1 and kwargs.get("engine") == "c":
81
warnings.warn(
82
"read_clipboard with regex separator does not work properly with c engine."
83
)
84
85
return read_csv(StringIO(text), sep=sep, **kwargs)
86
87
88
def to_clipboard(
89
obj, excel: bool | None = True, sep: str | None = None, **kwargs
90
) -> None: # pragma: no cover
91
"""
92
Attempt to write text representation of object to the system clipboard
93
The clipboard can be then pasted into Excel for example.
94
95
Parameters
96
----------
97
obj : the object to write to the clipboard
98
excel : bool, defaults to True
99
if True, use the provided separator, writing in a csv
100
format for allowing easy pasting into excel.
101
if False, write a string representation of the object
102
to the clipboard
103
sep : optional, defaults to tab
104
other keywords are passed to to_csv
105
106
Notes
107
-----
108
Requirements for your platform
109
- Linux: xclip, or xsel (with PyQt4 modules)
110
- Windows:
111
- OS X:
112
"""
113
encoding = kwargs.pop("encoding", "utf-8")
114
115
# testing if an invalid encoding is passed to clipboard
116
if encoding is not None and encoding.lower().replace("-", "") != "utf8":
117
raise ValueError("clipboard only supports utf-8 encoding")
118
119
from pandas.io.clipboard import clipboard_set
120
121
if excel is None:
122
excel = True
123
124
if excel:
125
try:
126
if sep is None:
127
sep = "\t"
128
buf = StringIO()
129
130
# clipboard_set (pyperclip) expects unicode
131
obj.to_csv(buf, sep=sep, encoding="utf-8", **kwargs)
132
text = buf.getvalue()
133
134
clipboard_set(text)
135
return
136
except TypeError:
137
warnings.warn(
138
"to_clipboard in excel mode requires a single character separator."
139
)
140
elif sep is not None:
141
warnings.warn("to_clipboard with excel=False ignores the sep argument.")
142
143
if isinstance(obj, ABCDataFrame):
144
# str(df) has various unhelpful defaults, like truncation
145
with option_context("display.max_colwidth", None):
146
objstr = obj.to_string(**kwargs)
147
else:
148
objstr = str(obj)
149
clipboard_set(objstr)
150
151