forked frombpython/bpython
- Notifications
You must be signed in to change notification settings - Fork0
Expand file tree
/
Copy pathurwid.py
More file actions
executable file
·758 lines (624 loc) · 27.4 KB
/
urwid.py
File metadata and controls
executable file
·758 lines (624 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#!/usr/bin/env python
#
# The MIT License
#
# Copyright (c) 2010 Marien Zwart
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""bpython backend based on Urwid.
Based on Urwid 0.9.9.
This steals many things from bpython's "cli" backend.
This is still *VERY* rough.
"""
from __future__importabsolute_import,with_statement,division
importsys
importos
importlocale
importsignal
fromtypesimportModuleType
fromoptparseimportOption
frompygments.tokenimportToken
frombpythonimportargsasbpargs,repl
frombpython.formatterimporttheme_map
frombpython.importcompletionimportfind_coroutine
importurwid
py3=sys.version_info[0]==3
Parenthesis=Token.Punctuation.Parenthesis
# Urwid colors are:
# 'black', 'dark red', 'dark green', 'brown', 'dark blue',
# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',
# 'light red', 'light green', 'yellow', 'light blue',
# 'light magenta', 'light cyan', 'white'
# and bpython has:
# blacK, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default
COLORMAP= {
'k':'black',
'r':'dark red',# or light red?
'g':'dark green',# or light green?
'y':'yellow',
'b':'dark blue',# or light blue?
'm':'dark magenta',# or light magenta?
'c':'dark cyan',# or light cyan?
'w':'white',
'd':'default',
}
try:
fromtwisted.internetimportprotocol
fromtwisted.protocolsimportbasic
exceptImportError:
pass
else:
classEvalProtocol(basic.LineOnlyReceiver):
delimiter='\n'
def__init__(self,myrepl):
self.repl=myrepl
deflineReceived(self,line):
# HACK!
# TODO: deal with encoding issues here...
self.repl.main_loop.process_input(line)
self.repl.main_loop.process_input(['enter'])
classEvalFactory(protocol.ServerFactory):
def__init__(self,myrepl):
self.repl=myrepl
defbuildProtocol(self,addr):
returnEvalProtocol(self.repl)
classStatusbar(object):
"""Statusbar object, ripped off from bpython.cli.
This class provides the status bar at the bottom of the screen.
It has message() and prompt() methods for user interactivity, as
well as settext() and clear() methods for changing its appearance.
The check() method needs to be called repeatedly if the statusbar is
going to be aware of when it should update its display after a message()
has been called (it'll display for a couple of seconds and then disappear).
It should be called as:
foo = Statusbar('Initial text to display')
or, for a blank statusbar:
foo = Statusbar()
The "widget" attribute is an urwid widget.
"""
def__init__(self,config,s=None):
self.config=config
self.s=sor''
# XXX wrap in AttrMap for wrapping?
self.widget=urwid.Text(('main',self.s))
defformat_tokens(tokensource):
fortoken,textintokensource:
iftext=='\n':
continue
# TODO: something about inversing Parenthesis
whiletokennotintheme_map:
token=token.parent
yield (theme_map[token],text)
classBPythonEdit(urwid.Edit):
"""Customized editor *very* tightly interwoven with URWIDRepl.
Changes include:
- The edit text supports markup, not just the caption.
This works by calling set_edit_markup from the change event
as well as whenever markup changes while text does not.
- The widget can be made readonly, which currently just means
it is no longer selectable and stops drawing the cursor.
This is currently a one-way operation, but that is just because
I only need and test the readwrite->readonly transition.
- move_cursor_to_coords is ignored
(except for internal calls from keypress or mouse_event).
- arrow up/down are ignored.
"""
def__init__(self,*args,**kwargs):
self._bpy_text=''
self._bpy_attr= []
self._bpy_selectable=True
self._bpy_may_move_cursor=False
urwid.Edit.__init__(self,*args,**kwargs)
defmake_readonly(self):
self._bpy_selectable=False
# This is necessary to prevent the listbox we are in getting
# fresh cursor coords of None from get_cursor_coords
# immediately after we go readonly and then getting a cached
# canvas that still has the cursor set. It spots that
# inconsistency and raises.
self._invalidate()
defset_edit_markup(self,markup):
"""Call this when markup changes but the underlying text does not.
You should arrange for this to be called from the 'change' signal.
"""
self._bpy_text,self._bpy_attr=urwid.decompose_tagmarkup(markup)
# This is redundant when we're called off the 'change' signal.
# I'm assuming this is cheap, making that ok.
self._invalidate()
defget_text(self):
returnself._caption+self._bpy_text,self._attrib+self._bpy_attr
defselectable(self):
returnself._bpy_selectable
defget_cursor_coords(self,*args,**kwargs):
# urwid gets confused if a nonselectable widget has a cursor position.
ifnotself._bpy_selectable:
returnNone
returnurwid.Edit.get_cursor_coords(self,*args,**kwargs)
defrender(self,size,focus=False):
# XXX I do not want to have to do this, but listbox gets confused
# if I do not (getting None out of get_cursor_coords because
# we just became unselectable, then having this render a cursor)
ifnotself._bpy_selectable:
focus=False
returnurwid.Edit.render(self,size,focus=focus)
defget_pref_col(self,size):
# Need to make this deal with us being nonselectable
ifnotself._bpy_selectable:
return'left'
returnurwid.Edit.get_pref_col(self,size)
defmove_cursor_to_coords(self,*args):
ifself._bpy_may_move_cursor:
returnurwid.Edit.move_cursor_to_coords(self,*args)
returnFalse
defkeypress(self,size,key):
self._bpy_may_move_cursor=True
try:
# Do not handle up/down arrow, leave them for the repl.
ifurwid.command_map[key]in ('cursor up','cursor down'):
returnkey
returnurwid.Edit.keypress(self,size,key)
finally:
self._bpy_may_move_cursor=False
defmouse_event(self,*args):
self._bpy_may_move_cursor=True
try:
returnurwid.Edit.mouse_event(self,*args)
finally:
self._bpy_may_move_cursor=False
classTooltip(urwid.BoxWidget):
"""Container inspired by Overlay to position our tooltip.
bottom_w should be a BoxWidget.
The top window currently has to be a listbox to support shrinkwrapping.
This passes keyboard events to the bottom instead of the top window.
It also positions the top window relative to the cursor position
from the bottom window and hides it if there is no cursor.
"""
def__init__(self,bottom_w,listbox):
self.__super.__init__()
self.bottom_w=bottom_w
self.listbox=listbox
# TODO: this linebox should use the 'main' color.
self.top_w=urwid.LineBox(listbox)
defselectable(self):
returnself.bottom_w.selectable()
defkeypress(self,size,key):
returnself.bottom_w.keypress(size,key)
defmouse_event(self,size,event,button,col,row,focus):
# TODO: pass to top widget if visible and inside it.
ifnothasattr(self.bottom_w,'mouse_event'):
returnFalse
returnself.bottom_w.mouse_event(
size,event,button,col,row,focus)
defget_cursor_coords(self,size):
returnself.bottom_w.get_cursor_coords(size)
defrender(self,size,focus=False):
maxcol,maxrow=size
bottom_c=self.bottom_w.render(size,focus)
cursor=bottom_c.cursor
ifnotcursor:
# Hide the tooltip if there is no cursor.
returnbottom_c
cursor_x,cursor_y=cursor
ifcursor_y*2<maxrow:
# Cursor is in the top half. Tooltip goes below it:
y=cursor_y+1
rows=maxrow-y
else:
# Cursor is in the bottom half. Tooltip fills the area above:
y=0
rows=cursor_y
# HACK: shrink-wrap the tooltip. This is ugly in multiple ways:
# - It only works on a listbox.
# - It assumes the wrapping LineBox eats one char on each edge.
# - It is a loop.
# (ideally it would check how much free space there is,
# instead of repeatedly trying smaller sizes)
while'bottom'inself.listbox.ends_visible((maxcol-2,rows-3)):
rows-=1
# If we're displaying above the cursor move the top edge down:
ifnoty:
y=cursor_y-rows
# The top window never gets focus.
top_c=self.top_w.render((maxcol,rows))
combi_c=urwid.CanvasOverlay(top_c,bottom_c,0,y)
# Use the cursor coordinates from the bottom canvas.
canvas=urwid.CompositeCanvas(combi_c)
canvas.cursor=cursor
returncanvas
classURWIDRepl(repl.Repl):
# XXX this is getting silly, need to split this up somehow
def__init__(self,main_loop,frame,listbox,overlay,tooltip,
interpreter,statusbar,config):
repl.Repl.__init__(self,interpreter,config)
self.main_loop=main_loop
self.frame=frame
self.listbox=listbox
self.overlay=overlay
self.tooltip=tooltip
self.edits= []
self.edit=None
self.statusbar=statusbar
# XXX repl.Repl uses this? What is it?
self.cpos=0
# Subclasses of Repl need to implement echo, current_line, cw
defecho(self,s):
s=s.rstrip('\n')
ifs:
text=urwid.Text(('output',s))
ifself.editisNone:
self.listbox.body.append(text)
else:
self.listbox.body.insert(-1,text)
# The edit widget should be focused and *stay* focused.
# XXX TODO: make sure the cursor stays in the same spot.
self.listbox.set_focus(len(self.listbox.body)-1)
# TODO: maybe do the redraw after a short delay
# (for performance)
self.main_loop.draw_screen()
defcurrent_line(self):
"""Return the current line (the one the cursor is in)."""
ifself.editisNone:
return''
returnself.edit.get_edit_text()
defcw(self):
"""Return the current word (incomplete word left of cursor)."""
ifself.editisNone:
return
pos=self.edit.edit_pos
text=self.edit.get_edit_text()
ifpos!=len(text):
# Disable autocomplete if not at end of line, like cli does.
return
# Stolen from cli. TODO: clean up and split out.
if (nottextor
(nottext[-1].isalnum()andtext[-1]notin ('.','_'))):
return
# Seek backwards in text for the first non-identifier char:
fori,cinenumerate(reversed(text)):
ifnotc.isalnum()andcnotin ('.','_'):
break
else:
# No non-identifiers, return everything.
returntext
# Return everything to the right of the non-identifier.
returntext[-i:]
def_populate_completion(self,main_loop,user_data):
widget_list=self.tooltip.body
widget_list[1]=urwid.Text('')
# This is just me flailing around wildly. TODO: actually write.
ifself.complete():
ifself.argspec:
# This is mostly just stolen from the cli module.
func_name,args,is_bound,in_arg=self.argspec
args,varargs,varkw,defaults=args[:4]
ifpy3:
kwonly,kwonly_defaults=args[4:]
else:
kwonly,kwonly_defaults= [], {}
markup= [('bold name',func_name),
('name',': (')]
# the isinstance checks if we're in a positional arg
# (instead of a keyword arg), I think
ifis_boundandisinstance(in_arg,int):
in_arg+=1
# bpython.cli checks if this goes off the edge and
# does clever wrapping. I do not (yet).
fork,iinenumerate(args):
ifdefaultsandk+1>len(args)-len(defaults):
kw=str(defaults[k- (len(args)-len(defaults))])
else:
kw=None
ifnotkandstr(i)=='self':
color='name'
else:
color='token'
ifk==in_argori==in_arg:
color='bold '+color
markup.append((color,str(i)))
ifkw:
markup.extend([('punctuation','='),
('token',kw)])
ifk!=len(args)-1:
markup.append(('punctuation',', '))
ifvarargs:
ifargs:
markup.append(('punctuation',', '))
markup.append(('token','*'+varargs))
ifkwonly:
ifnotvarargs:
ifargs:
markup.append(('punctuation',', '))
markup.append(('punctuation','*'))
forarginkwonly:
ifarg==in_arg:
color='bold token'
else:
color='token'
markup.extend([('punctuation',', '),
(color,arg)])
ifarginkwonly_defaults:
markup.extend([('punctuation','='),
('token',kwonly_defaults[arg])])
ifvarkw:
ifargsorvarargsorkwonly:
markup.append(('punctuation',', '))
markup.append(('token','**'+varkw))
markup.append(('punctuation',')'))
else:
markup=''
widget_list[0].set_text(markup)
ifself.matches:
texts= [urwid.Text(('main',match))
formatchinself.matches]
width=max(text.pack()[0]fortextintexts)
gridflow=urwid.GridFlow(texts,width,1,0,'left')
widget_list[1]=gridflow
self.frame.body=self.overlay
else:
self.frame.body=self.listbox
ifself.docstring:
# TODO: use self.format_docstring? needs a width/height...
docstring=self.docstring
else:
docstring=''
widget_list[2].set_text(('comment',docstring))
defreprint_line(self,lineno,tokens):
edit=self.edits[-len(self.buffer)+lineno-1]
edit.set_edit_markup(list(format_tokens(tokens)))
defpush(self,s,insert_into_history=True):
# Restore the original SIGINT handler. This is needed to be able
# to break out of infinite loops. If the interpreter itself
# sees this it prints 'KeyboardInterrupt' and returns (good).
orig_handler=signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT,signal.default_int_handler)
# Pretty blindly adapted from bpython.cli
try:
returnrepl.Repl.push(self,s,insert_into_history)
exceptSystemExit:
raiseurwid.ExitMainLoop()
exceptKeyboardInterrupt:
# KeyboardInterrupt happened between the except block around
# user code execution and this code. This should be rare,
# but make sure to not kill bpython here, so leaning on
# ctrl+c to kill buggy code running inside bpython is safe.
self.keyboard_interrupt()
finally:
signal.signal(signal.SIGINT,orig_handler)
defstart(self):
# Stolen from bpython.cli again
self.push('from bpython._internal import _help as help\n',False)
self.prompt(False)
defkeyboard_interrupt(self):
# Do we need to do more here? Break out of multiline input perhaps?
self.echo('KeyboardInterrupt')
defprompt(self,more):
# XXX is this the right place?
self.rl_history.reset()
# XXX what is s_hist?
ifnotmore:
self.edit=BPythonEdit(caption=('prompt','>>> '))
self.stdout_hist+='>>> '
else:
self.edit=BPythonEdit(caption=('prompt_more','... '))
self.stdout_hist+='... '
urwid.connect_signal(self.edit,'change',self.on_input_change)
# Do this after connecting the change signal handler:
self.edit.insert_text(4*self.next_indentation()*' ')
self.edits.append(self.edit)
self.listbox.body.append(self.edit)
self.listbox.set_focus(len(self.listbox.body)-1)
# Hide the tooltip
self.frame.body=self.listbox
defon_input_change(self,edit,text):
tokens=self.tokenize(text,False)
edit.set_edit_markup(list(format_tokens(tokens)))
# If we call this synchronously the get_edit_text() in repl.cw
# still returns the old text...
self.main_loop.set_alarm_in(0,self._populate_completion)
defhandle_input(self,event):
ifevent=='enter':
inp=self.edit.get_edit_text()
self.history.append(inp)
self.edit.make_readonly()
# XXX what is this s_hist thing?
self.stdout_hist+=inp+'\n'
self.edit=None
# This may take a while, so force a redraw first:
self.main_loop.draw_screen()
more=self.push(inp)
self.prompt(more)
elifevent=='ctrl d':
# ctrl+d on an empty line exits
ifself.editisnotNoneandnotself.edit.get_edit_text():
raiseurwid.ExitMainLoop()
elifurwid.command_map[event]=='cursor up':
# "back" from bpython.cli
self.cpos=0
self.rl_history.enter(self.edit.get_edit_text())
self.edit.set_edit_text('')
self.edit.insert_text(self.rl_history.back())
elifurwid.command_map[event]=='cursor down':
# "fwd" from bpython.cli
self.cpos=0
self.rl_history.enter(self.edit.get_edit_text())
self.edit.set_edit_text('')
self.edit.insert_text(self.rl_history.forward())
#else:
# self.echo(repr(event))
defmain(args=None,locals_=None,banner=None):
# Err, somewhat redundant. There is a call to this buried in urwid.util.
# That seems unfortunate though, so assume that's going away...
locale.setlocale(locale.LC_ALL,'')
# TODO: maybe support displays other than raw_display?
config,options,exec_args=bpargs.parse(args, (
'Urwid options',None, [
Option('--reactor','-r',
help='Run a reactor (see --help-reactors)'),
Option('--help-reactors',action='store_true',
help='List available reactors for -r'),
Option('--server','-s',type='int',
help='Port to run an eval server on (forces Twisted)'),
]))
ifoptions.help_reactors:
fromtwisted.applicationimportreactors
# Stolen from twisted.application.app (twistd).
forrinreactors.getReactorTypes():
print' %-4s\t%s'% (r.shortName,r.description)
return
palette= [
(name,COLORMAP[color.lower()],'default',
'bold'ifcolor.isupper()else'default')
forname,colorinconfig.color_scheme.iteritems()]
palette.extend([
('bold '+name,color+',bold',background,monochrome)
forname,color,background,monochromeinpalette])
ifoptions.serverandnotoptions.reactor:
options.reactor='select'
ifoptions.reactor:
fromtwisted.applicationimportreactors
try:
# XXX why does this not just return the reactor it installed?
reactor=reactors.installReactor(options.reactor)
ifreactorisNone:
fromtwisted.internetimportreactor
exceptreactors.NoSuchReactor:
sys.stderr.write('Reactor %s does not exist\n'% (
options.reactor,))
return
event_loop=urwid.TwistedEventLoop(reactor)
else:
# None, not urwid.SelectEventLoop(), to work with
# screens that do not support external event loops.
event_loop=None
# TODO: there is also a glib event loop. Do we want that one?
listbox=urwid.ListBox(urwid.SimpleListWalker([]))
# String is straight from bpython.cli
statusbar=Statusbar(
config,
" <%s> Rewind <%s> Save <%s> Pastebin <%s> Pager <%s> Show Source "%
(config.undo_key,config.save_key,
config.pastebin_key,config.last_output_key,
config.show_source_key))
tooltip=urwid.ListBox(urwid.SimpleListWalker([
urwid.Text(''),urwid.Text(''),urwid.Text('')]))
overlay=Tooltip(listbox,tooltip)
frame=urwid.Frame(overlay,footer=statusbar.widget)
# __main__ construction from bpython.cli
iflocals_isNone:
main_mod=sys.modules['__main__']=ModuleType('__main__')
locals_=main_mod.__dict__
interpreter=repl.Interpreter(locals_,locale.getpreferredencoding())
# This constructs a raw_display.Screen, which nabs sys.stdin/out.
loop=urwid.MainLoop(frame,palette,event_loop=event_loop)
myrepl=URWIDRepl(loop,frame,listbox,overlay,tooltip,
interpreter,statusbar,config)
ifoptions.server:
factory=EvalFactory(myrepl)
reactor.listenTCP(options.server,factory,interface='127.0.0.1')
ifoptions.reactor:
# Twisted sets a sigInt handler that stops the reactor unless
# it sees a different custom signal handler.
defsigint(*args):
reactor.callFromThread(myrepl.keyboard_interrupt)
signal.signal(signal.SIGINT,sigint)
# XXX HACK: circular dependency between the event loop and repl.
# Fix by not using unhandled_input?
loop._unhandled_input=myrepl.handle_input
# Save stdin, stdout and stderr for later restoration
orig_stdin=sys.stdin
orig_stdout=sys.stdout
orig_stderr=sys.stderr
# urwid's screen start() and stop() calls currently hit sys.stdin
# directly (via RealTerminal.tty_signal_keys), so start the screen
# before swapping sys.std*, and swap them back before restoring
# the screen. This also avoids crashes if our redirected sys.std*
# are called before we get around to starting the mainloop
# (urwid raises an exception if we try to draw to the screen
# before starting it).
defrun_with_screen_before_mainloop():
try:
# Currently we just set this to None because I do not
# expect code hitting stdin to work. For example: exit()
# (not sys.exit, site.py's exit) tries to close sys.stdin,
# which breaks urwid's shutdown. bpython.cli sets this to
# a fake object that reads input through curses and
# returns it. When using twisted I do not think we can do
# that because sys.stdin.read and friends block, and we
# cannot re-enter the reactor. If using urwid's own
# mainloop we *might* be able to do something similar and
# re-enter its mainloop.
sys.stdin=None#FakeStdin(myrepl)
sys.stdout=myrepl
sys.stderr=myrepl
loop.set_alarm_in(0,start)
whileTrue:
try:
loop.run()
exceptKeyboardInterrupt:
# HACK: if we run under a twisted mainloop this should
# never happen: we have a SIGINT handler set.
# If we use the urwid select-based loop we just restart
# that loop if interrupted, instead of trying to cook
# up an equivalent to reactor.callFromThread (which
# is what our Twisted sigint handler does)
loop.set_alarm_in(
0,lambda*args:myrepl.keyboard_interrupt())
continue
break
ifconfig.hist_length:
histfilename=os.path.expanduser(config.hist_file)
myrepl.rl_history.save(histfilename,
locale.getpreferredencoding())
finally:
sys.stdin=orig_stdin
sys.stderr=orig_stderr
sys.stdout=orig_stdout
# This needs more thought. What needs to happen inside the mainloop?
defstart(main_loop,user_data):
ifexec_args:
bpargs.exec_code(interpreter,exec_args)
ifnotoptions.interactive:
raiseurwid.ExitMainLoop()
ifnotexec_args:
sys.path.insert(0,'')
# this is CLIRepl.startup inlined.
filename=os.environ.get('PYTHONSTARTUP')
iffilenameandos.path.isfile(filename):
withopen(filename,'r')asf:
ifpy3:
interpreter.runsource(f.read(),filename,'exec')
else:
interpreter.runsource(f.read(),filename,'exec',
encode=False)
ifbannerisnotNone:
repl.write(banner)
repl.write('\n')
myrepl.start()
# This bypasses main_loop.set_alarm_in because we must *not*
# hit the draw_screen call (it's unnecessary and slow).
defrun_find_coroutine():
iffind_coroutine():
main_loop.event_loop.alarm(0,run_find_coroutine)
run_find_coroutine()
loop.screen.run_wrapper(run_with_screen_before_mainloop)
ifconfig.flush_outputandnotoptions.quiet:
sys.stdout.write(myrepl.getstdout())
sys.stdout.flush()
if__name__=='__main__':
main()