Skip to content

Commit fa23602

Browse files
committed
1 parent 7734845 commit fa23602

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

.github/workflows/ci.yml

+5
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ jobs:
3131
PYTHONIOENCODING: utf-8
3232
PYTHONUTF8: 1
3333
run: pytest --cov agate
34+
- name: Read from stdin
35+
if: matrix.os != 'windows-latest'
36+
run: python -c 'import sys; import agate; agate.Table.from_csv(sys.stdin, sniff_limit=1)' < examples/test.csv
37+
- name: Read from pipe
38+
run: printf 'a,b,c\n1,2,3' | python -c 'import sys; import agate; agate.Table.from_csv(sys.stdin, sniff_limit=1)'
3439
- run: python charts.py
3540
- env:
3641
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

CHANGELOG.rst

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
Unreleased
2+
----------
3+
4+
- fix: Version 1.10.0 errors on piped data.
5+
16
1.10.1 - April 28, 2024
27
-----------------------
38

agate/table/from_csv.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import io
12
import itertools
2-
from io import StringIO
3+
import sys
34

45

56
@classmethod
@@ -63,14 +64,23 @@ def from_csv(cls, path, column_names=None, column_types=None, row_names=None, sk
6364

6465
if sniff_limit is None:
6566
# Reads to the end of the tile, but avoid reading the file twice.
66-
handle = StringIO(f.read())
67-
kwargs['dialect'] = csv.Sniffer().sniff(handle.getvalue())
67+
handle = io.StringIO(f.read())
68+
sample = handle.getvalue()
6869
elif sniff_limit > 0:
69-
offset = f.tell()
70+
if f == sys.stdin:
71+
# "At most one single read on the raw stream is done to satisfy the call. The number of bytes returned
72+
# may be less or more than requested." In other words, it reads the buffer_size, which might be less or
73+
# more than the sniff_limit. On my machine, the buffer_size of sys.stdin.buffer is the length of the
74+
# input, up to 65536. This assumes that users don't sniff more than 64 KiB.
75+
# https://docs.python.org/3/library/io.html#io.BufferedReader.peek
76+
sample = sys.stdin.buffer.peek(sniff_limit).decode(encoding, 'ignore')[:sniff_limit] # reads *bytes*
77+
else:
78+
offset = f.tell()
79+
sample = f.read(sniff_limit) # reads *characters*
80+
f.seek(offset) # can't do f.seek(-sniff_limit, os.SEEK_CUR) on file opened in text mode
7081

71-
# Reads only the start of the file.
72-
kwargs['dialect'] = csv.Sniffer().sniff(f.read(sniff_limit))
73-
f.seek(offset)
82+
if sniff_limit is None or sniff_limit > 0:
83+
kwargs['dialect'] = csv.Sniffer().sniff(sample)
7484

7585
reader = csv.reader(handle, header=header, **kwargs)
7686

0 commit comments

Comments
 (0)