Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/pandas/io/clipboards.py: 10%

56 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1""" io on the clipboard """ 

2from __future__ import annotations 

3 

4from io import StringIO 

5import warnings 

6 

7from pandas.util._exceptions import find_stack_level 

8 

9from pandas.core.dtypes.generic import ABCDataFrame 

10 

11from pandas import ( 

12 get_option, 

13 option_context, 

14) 

15 

16 

17def read_clipboard(sep: str = r"\s+", **kwargs): # pragma: no cover 

18 r""" 

19 Read text from clipboard and pass to read_csv. 

20 

21 Parameters 

22 ---------- 

23 sep : str, default '\s+' 

24 A string or regex delimiter. The default of '\s+' denotes 

25 one or more whitespace characters. 

26 

27 **kwargs 

28 See read_csv for the full argument list. 

29 

30 Returns 

31 ------- 

32 DataFrame 

33 A parsed DataFrame object. 

34 """ 

35 encoding = kwargs.pop("encoding", "utf-8") 

36 

37 # only utf-8 is valid for passed value because that's what clipboard 

38 # supports 

39 if encoding is not None and encoding.lower().replace("-", "") != "utf8": 

40 raise NotImplementedError("reading from clipboard only supports utf-8 encoding") 

41 

42 from pandas.io.clipboard import clipboard_get 

43 from pandas.io.parsers import read_csv 

44 

45 text = clipboard_get() 

46 

47 # Try to decode (if needed, as "text" might already be a string here). 

48 try: 

49 text = text.decode(kwargs.get("encoding") or get_option("display.encoding")) 

50 except AttributeError: 

51 pass 

52 

53 # Excel copies into clipboard with \t separation 

54 # inspect no more then the 10 first lines, if they 

55 # all contain an equal number (>0) of tabs, infer 

56 # that this came from excel and set 'sep' accordingly 

57 lines = text[:10000].split("\n")[:-1][:10] 

58 

59 # Need to remove leading white space, since read_csv 

60 # accepts: 

61 # a b 

62 # 0 1 2 

63 # 1 3 4 

64 

65 counts = {x.lstrip(" ").count("\t") for x in lines} 

66 if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: 

67 sep = "\t" 

68 # check the number of leading tabs in the first line 

69 # to account for index columns 

70 index_length = len(lines[0]) - len(lines[0].lstrip(" \t")) 

71 if index_length != 0: 

72 kwargs.setdefault("index_col", list(range(index_length))) 

73 

74 # Edge case where sep is specified to be None, return to default 

75 if sep is None and kwargs.get("delim_whitespace") is None: 

76 sep = r"\s+" 

77 

78 # Regex separator currently only works with python engine. 

79 # Default to python if separator is multi-character (regex) 

80 if len(sep) > 1 and kwargs.get("engine") is None: 

81 kwargs["engine"] = "python" 

82 elif len(sep) > 1 and kwargs.get("engine") == "c": 

83 warnings.warn( 

84 "read_clipboard with regex separator does not work properly with c engine.", 

85 stacklevel=find_stack_level(), 

86 ) 

87 

88 return read_csv(StringIO(text), sep=sep, **kwargs) 

89 

90 

91def to_clipboard( 

92 obj, excel: bool | None = True, sep: str | None = None, **kwargs 

93) -> None: # pragma: no cover 

94 """ 

95 Attempt to write text representation of object to the system clipboard 

96 The clipboard can be then pasted into Excel for example. 

97 

98 Parameters 

99 ---------- 

100 obj : the object to write to the clipboard 

101 excel : bool, defaults to True 

102 if True, use the provided separator, writing in a csv 

103 format for allowing easy pasting into excel. 

104 if False, write a string representation of the object 

105 to the clipboard 

106 sep : optional, defaults to tab 

107 other keywords are passed to to_csv 

108 

109 Notes 

110 ----- 

111 Requirements for your platform 

112 - Linux: xclip, or xsel (with PyQt4 modules) 

113 - Windows: 

114 - OS X: 

115 """ 

116 encoding = kwargs.pop("encoding", "utf-8") 

117 

118 # testing if an invalid encoding is passed to clipboard 

119 if encoding is not None and encoding.lower().replace("-", "") != "utf8": 

120 raise ValueError("clipboard only supports utf-8 encoding") 

121 

122 from pandas.io.clipboard import clipboard_set 

123 

124 if excel is None: 

125 excel = True 

126 

127 if excel: 

128 try: 

129 if sep is None: 

130 sep = "\t" 

131 buf = StringIO() 

132 

133 # clipboard_set (pyperclip) expects unicode 

134 obj.to_csv(buf, sep=sep, encoding="utf-8", **kwargs) 

135 text = buf.getvalue() 

136 

137 clipboard_set(text) 

138 return 

139 except TypeError: 

140 warnings.warn( 

141 "to_clipboard in excel mode requires a single character separator.", 

142 stacklevel=find_stack_level(), 

143 ) 

144 elif sep is not None: 

145 warnings.warn( 

146 "to_clipboard with excel=False ignores the sep argument.", 

147 stacklevel=find_stack_level(), 

148 ) 

149 

150 if isinstance(obj, ABCDataFrame): 

151 # str(df) has various unhelpful defaults, like truncation 

152 with option_context("display.max_colwidth", None): 

153 objstr = obj.to_string(**kwargs) 

154 else: 

155 objstr = str(obj) 

156 clipboard_set(objstr)