| 1 |
from rpython.rlib.rutf8 import Utf8StringIterator, Utf8StringBuilder |
| 2 |
from rpython.rlib import objectmodel |
| 3 |
from pypy.interpreter.baseobjspace import W_Root |
| 4 |
from pypy.interpreter.error import OperationError |
| 5 |
from pypy.interpreter.typedef import TypeDef, interp2app |
| 6 |
from pypy.interpreter.typedef import interp_attrproperty_w |
| 7 |
from pypy.module._csv.interp_csv import _build_dialect, NOT_SET |
| 8 |
from pypy.module._csv.interp_csv import (QUOTE_MINIMAL, QUOTE_ALL, |
| 9 |
QUOTE_NONNUMERIC, QUOTE_NONE) |
| 10 |
|
| 11 |
|
| 12 |
class W_Writer(W_Root): |
| 13 |
def __init__(self, space, dialect, w_fileobj): |
| 14 |
self.space = space |
| 15 |
self.dialect = dialect |
| 16 |
self.w_filewrite = space.getattr(w_fileobj, space.newtext('write')) |
| 17 |
|
| 18 |
special = [dialect.delimiter, ord('\r'), ord('\n')] |
| 19 |
for c in Utf8StringIterator(dialect.lineterminator): |
| 20 |
special.append(c) |
| 21 |
if dialect.escapechar != 0: |
| 22 |
special.append(dialect.escapechar) |
| 23 |
if dialect.quotechar != 0: |
| 24 |
special.append(dialect.quotechar) |
| 25 |
self.special_characters = special |
| 26 |
|
| 27 |
@objectmodel.dont_inline |
| 28 |
def error(self, msg): |
| 29 |
space = self.space |
| 30 |
w_module = space.getbuiltinmodule('_csv') |
| 31 |
w_error = space.getattr(w_module, space.newtext('Error')) |
| 32 |
return OperationError(w_error, space.newtext(msg)) |
| 33 |
|
| 34 |
def writerow(self, w_fields): |
| 35 |
"""Construct and write a CSV record from a sequence of fields. |
| 36 |
Non-string elements will be converted to string.""" |
| 37 |
space = self.space |
| 38 |
try: |
| 39 |
fields_w = space.listview(w_fields) |
| 40 |
except OperationError as e: |
| 41 |
if e.match(space, space.w_TypeError): |
| 42 |
raise self.error("iterable expected, not %s" % space.repr(w_fields)) |
| 43 |
raise e |
| 44 |
|
| 45 |
dialect = self.dialect |
| 46 |
rec = Utf8StringBuilder(80) |
| 47 |
|
| 48 |
for field_index in range(len(fields_w)): |
| 49 |
w_field = fields_w[field_index] |
| 50 |
if space.is_w(w_field, space.w_None): |
| 51 |
field = "" |
| 52 |
length = 0 |
| 53 |
elif space.isinstance_w(w_field, space.w_float): |
| 54 |
field, length = space.utf8_len_w(space.repr(w_field)) |
| 55 |
else: |
| 56 |
field, length = space.utf8_len_w(space.str(w_field)) |
| 57 |
|
| 58 |
if dialect.quoting == QUOTE_NONNUMERIC: |
| 59 |
try: |
| 60 |
space.float_w(w_field) |
| 61 |
quoted = False |
| 62 |
except OperationError as e: |
| 63 |
if e.async(space): |
| 64 |
raise |
| 65 |
quoted = True |
| 66 |
elif dialect.quoting == QUOTE_ALL: |
| 67 |
quoted = True |
| 68 |
elif dialect.quoting == QUOTE_MINIMAL: |
| 69 |
|
| 70 |
special_characters = self.special_characters |
| 71 |
for c in Utf8StringIterator(field): |
| 72 |
if c not in special_characters: |
| 73 |
continue |
| 74 |
if c == dialect.escapechar: |
| 75 |
|
| 76 |
continue |
| 77 |
if c != dialect.quotechar or dialect.doublequote: |
| 78 |
quoted = True |
| 79 |
break |
| 80 |
else: |
| 81 |
quoted = False |
| 82 |
else: |
| 83 |
quoted = False |
| 84 |
if len(field) == 0: |
| 85 |
if dialect.delimiter == ord(' ') and dialect.skipinitialspace: |
| 86 |
if dialect.quoting == QUOTE_NONE: |
| 87 |
raise self.error( |
| 88 |
"empty field must be quoted if delimiter is a space " |
| 89 |
"and skipinitialspace is true") |
| 90 |
quoted = True |
| 91 |
|
| 92 |
|
| 93 |
if len(fields_w) == 1: |
| 94 |
if dialect.quoting == QUOTE_NONE: |
| 95 |
raise self.error("single empty field record " |
| 96 |
"must be quoted") |
| 97 |
quoted = True |
| 98 |
|
| 99 |
|
| 100 |
if field_index > 0: |
| 101 |
rec.append_code(dialect.delimiter) |
| 102 |
|
| 103 |
|
| 104 |
if quoted: |
| 105 |
rec.append_code(dialect.quotechar) |
| 106 |
|
| 107 |
|
| 108 |
special_characters = self.special_characters |
| 109 |
for c in Utf8StringIterator(field): |
| 110 |
if c in special_characters: |
| 111 |
if dialect.quoting == QUOTE_NONE: |
| 112 |
want_escape = True |
| 113 |
else: |
| 114 |
want_escape = False |
| 115 |
if c == dialect.quotechar: |
| 116 |
if dialect.doublequote: |
| 117 |
rec.append_code(dialect.quotechar) |
| 118 |
else: |
| 119 |
want_escape = True |
| 120 |
if c == dialect.escapechar: |
| 121 |
want_escape = True |
| 122 |
if want_escape: |
| 123 |
if dialect.escapechar == NOT_SET: |
| 124 |
raise self.error("need to escape, " |
| 125 |
"but no escapechar set") |
| 126 |
rec.append_code(dialect.escapechar) |
| 127 |
else: |
| 128 |
assert quoted |
| 129 |
|
| 130 |
rec.append_code(c) |
| 131 |
|
| 132 |
|
| 133 |
if quoted: |
| 134 |
rec.append_code(dialect.quotechar) |
| 135 |
|
| 136 |
|
| 137 |
rec.append(dialect.lineterminator) |
| 138 |
|
| 139 |
line = rec.build() |
| 140 |
return space.call_function(self.w_filewrite, space.newutf8(line, rec.getlength())) |
| 141 |
|
| 142 |
def writerows(self, w_seqseq): |
| 143 |
"""Construct and write a series of sequences to a csv file. |
| 144 |
Non-string elements will be converted to string.""" |
| 145 |
space = self.space |
| 146 |
w_iter = space.iter(w_seqseq) |
| 147 |
while True: |
| 148 |
try: |
| 149 |
w_seq = space.next(w_iter) |
| 150 |
except OperationError as e: |
| 151 |
if e.match(space, space.w_StopIteration): |
| 152 |
break |
| 153 |
raise |
| 154 |
self.writerow(w_seq) |
| 155 |
|
| 156 |
|
| 157 |
def csv_writer(space, w_fileobj, w_dialect=None, |
| 158 |
w_delimiter = None, |
| 159 |
w_doublequote = None, |
| 160 |
w_escapechar = None, |
| 161 |
w_lineterminator = None, |
| 162 |
w_quotechar = None, |
| 163 |
w_quoting = None, |
| 164 |
w_skipinitialspace = None, |
| 165 |
w_strict = None, |
| 166 |
): |
| 167 |
""" |
| 168 |
csv_writer = csv.writer(fileobj [, dialect='excel'] |
| 169 |
[optional keyword args]) |
| 170 |
for row in sequence: |
| 171 |
csv_writer.writerow(row) |
| 172 |
|
| 173 |
[or] |
| 174 |
|
| 175 |
csv_writer = csv.writer(fileobj [, dialect='excel'] |
| 176 |
[optional keyword args]) |
| 177 |
csv_writer.writerows(rows) |
| 178 |
|
| 179 |
The \"fileobj\" argument can be any object that supports the file API.""" |
| 180 |
dialect = _build_dialect(space, w_dialect, w_delimiter, w_doublequote, |
| 181 |
w_escapechar, w_lineterminator, w_quotechar, |
| 182 |
w_quoting, w_skipinitialspace, w_strict) |
| 183 |
return W_Writer(space, dialect, w_fileobj) |
| 184 |
|
| 185 |
W_Writer.typedef = TypeDef( |
| 186 |
'_csv.writer', |
| 187 |
dialect = interp_attrproperty_w('dialect', W_Writer), |
| 188 |
writerow = interp2app(W_Writer.writerow), |
| 189 |
writerows = interp2app(W_Writer.writerows), |
| 190 |
__doc__ = """CSV writer |
| 191 |
|
| 192 |
Writer objects are responsible for generating tabular data |
| 193 |
in CSV format from sequence input.""") |
| 194 |
W_Writer.typedef.acceptable_as_base_class = False |