Skip to content

Commit 14e1a6d

Browse files
committed
Add parameters to readfile and add test
1 parent ebc218a commit 14e1a6d

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

py/file.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ func init() {
3131
FileType.Dict["flush"] = MustNewMethod("flush", func(self Object) (Object, error) {
3232
return self.(*File).Flush()
3333
}, 0, "flush() -> Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.")
34-
FileType.Dict["readline"] = MustNewMethod("readline", func(self Object) (Object, error) {
35-
return self.(*File).Readline()
36-
}, 0, "readline() -> next line from the file, as a string.\n\nRetains newline. A non-empty string returned implies that readline() returned\na line, empty string returned implies that EOF is reached.")
34+
FileType.Dict["readline"] = MustNewMethod("readline", func(self Object, args Tuple, kwargs StringDict) (Object, error) {
35+
return self.(*File).ReadLine(args, kwargs)
36+
}, 0, "readline(size=-1, /) -> Read and return one line from the stream. If size is specified, at most size bytes will be read.\n\nThe line terminator is always b'\\n' for binary files; for text files, the newline argument to open can be used to select the line terminator(s) recognized.")
3737
}
3838

3939
type FileMode int
@@ -146,10 +146,27 @@ func (o *File) Read(args Tuple, kwargs StringDict) (Object, error) {
146146
return o.readResult(b)
147147
}
148148

149-
func (o *File) Readline() (Object, error) {
149+
func (o *File) ReadLine(args Tuple, kwargs StringDict) (Object, error) {
150+
var size Object = None
151+
err := UnpackTuple(args, kwargs, "readline", 0, 1, &size)
152+
if err != nil {
153+
return nil, err
154+
}
155+
limit := int64(-1)
156+
if size != None {
157+
pyN, ok := size.(Int)
158+
if !ok {
159+
return nil, ExceptionNewf(TypeError, "integer argument expected, got '%s'", size.Type().Name)
160+
}
161+
limit, _ = pyN.GoInt64()
162+
}
163+
150164
var buf []byte
151165
b := make([]byte, 1)
152166
for {
167+
if limit >= 0 && int64(len(buf)) >= limit {
168+
break
169+
}
153170
n, err := o.File.Read(b)
154171
if n > 0 {
155172
buf = append(buf, b[0])

py/tests/file.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@
2525
b = f.read()
2626
assert b == ''
2727

28+
doc = "readline"
29+
f2 = open(__file__)
30+
line = f2.readline()
31+
assert line == '# Copyright 2018 The go-python Authors. All rights reserved.\n'
32+
f2.close()
33+
2834
doc = "write"
2935
assertRaises(TypeError, f.write, 42)
3036

0 commit comments

Comments
 (0)