Skip to content

Commit 9741764

Browse files
committed
Implement readlines() and read() methods of FakeStdin.
This will close issue #52.
1 parent 8e81073 commit 9741764

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

bpython/cli.py

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -171,49 +171,78 @@ def __init__(self, interface):
171171

172172
self.encoding = getpreferredencoding()
173173
self.interface = interface
174+
self.buffer = list()
175+
176+
def __iter__(self):
177+
return iter(self.readlines())
174178

175179
def isatty(self):
176180
return True
177181

178-
def readline(self):
182+
def readline(self, size=-1):
179183
"""I can't think of any reason why anything other than readline would
180184
be useful in the context of an interactive interpreter so this is the
181185
only one I've done anything with. The others are just there in case
182186
someone does something weird to stop it from blowing up."""
183187

188+
if not size:
189+
return ''
190+
elif self.buffer:
191+
buffer = self.buffer.pop(0)
192+
else:
193+
buffer = ''
194+
184195
curses.raw(True)
185-
buffer = ''
186196
try:
187-
while True:
197+
while not buffer.endswith('\n'):
188198
key = self.interface.get_key()
189199
if key in [curses.erasechar(), 'KEY_BACKSPACE']:
190200
y, x = self.interface.scr.getyx()
191201
if buffer:
192202
self.interface.scr.delch(y, x - 1)
193203
buffer = buffer[:-1]
194204
continue
205+
elif key == chr(4) and not buffer:
206+
# C-d
207+
return ''
195208
elif (key != '\n' and
196209
(len(key) > 1 or unicodedata.category(key) == 'Cc')):
197210
continue
198211
sys.stdout.write(key)
199212
# Include the \n in the buffer - raw_input() seems to deal with trailing
200213
# linebreaks and will break if it gets an empty string.
201214
buffer += key
202-
if key == '\n':
203-
break
204215
finally:
205216
curses.raw(False)
206217

218+
if size > 0:
219+
rest = buffer[size:]
220+
if rest:
221+
self.buffer.append(rest)
222+
buffer = buffer[:size]
223+
207224
if py3:
208225
return buffer
209226
else:
210227
return buffer.encode(getpreferredencoding())
211228

212-
def read(self, x):
213-
pass
229+
def read(self, size=None):
230+
if size == 0:
231+
return ''
214232

215-
def readlines(self, x):
216-
pass
233+
data = list()
234+
while size is None or size > 0:
235+
line = self.readline(size or -1)
236+
if not line:
237+
break
238+
if size is not None:
239+
size -= len(line)
240+
data.append(line)
241+
242+
return ''.join(data)
243+
244+
def readlines(self, size=-1):
245+
return list(iter(self.readline, ''))
217246

218247
OPTS = Struct()
219248
DO_RESIZE = False

0 commit comments

Comments
 (0)