r""" >>> import io >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n")) 'abcd' >>> read_stringnl(io.BytesIO(b"\n")) Traceback (most recent call last): ... ValueError: no string quotes around b'' >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False) '' >>> read
(f, decode=True, stripquotes=True, *, encoding='latin-1')
| 313 | |
| 314 | |
| 315 | def read_stringnl(f, decode=True, stripquotes=True, *, encoding='latin-1'): |
| 316 | r""" |
| 317 | >>> import io |
| 318 | >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n")) |
| 319 | 'abcd' |
| 320 | |
| 321 | >>> read_stringnl(io.BytesIO(b"\n")) |
| 322 | Traceback (most recent call last): |
| 323 | ... |
| 324 | ValueError: no string quotes around b'' |
| 325 | |
| 326 | >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False) |
| 327 | '' |
| 328 | |
| 329 | >>> read_stringnl(io.BytesIO(b"''\n")) |
| 330 | '' |
| 331 | |
| 332 | >>> read_stringnl(io.BytesIO(b'"abcd"')) |
| 333 | Traceback (most recent call last): |
| 334 | ... |
| 335 | ValueError: no newline found when trying to read stringnl |
| 336 | |
| 337 | Embedded escapes are undone in the result. |
| 338 | >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'")) |
| 339 | 'a\n\\b\x00c\td' |
| 340 | """ |
| 341 | |
| 342 | data = f.readline() |
| 343 | if not data.endswith(b'\n'): |
| 344 | raise ValueError("no newline found when trying to read stringnl") |
| 345 | data = data[:-1] # lose the newline |
| 346 | |
| 347 | if stripquotes: |
| 348 | for q in (b'"', b"'"): |
| 349 | if data.startswith(q): |
| 350 | if not data.endswith(q): |
| 351 | raise ValueError("string quote %r not found at both " |
| 352 | "ends of %r" % (q, data)) |
| 353 | data = data[1:-1] |
| 354 | break |
| 355 | else: |
| 356 | raise ValueError("no string quotes around %r" % data) |
| 357 | |
| 358 | if decode: |
| 359 | data = codecs.escape_decode(data)[0].decode(encoding) |
| 360 | return data |
| 361 | |
| 362 | stringnl = ArgumentDescriptor( |
| 363 | name='stringnl', |
no test coverage detected
searching dependent graphs…