1 import logging
2 import sys
3 import StringIO
4
5 import turbogears
6 import pkg_resources
7 from turbogears import controllers, expose
8 from code import InteractiveConsole
9
10
11 log = logging.getLogger('turbogears.toolbox')
12
13
14 -class WebConsole(controllers.RootController):
15 """Web based Python interpreter"""
16
17 __label__ = 'WebConsole'
18
19 icon = "/tg_static/images/shell.png"
20
22 self.console = None
23
24 try:
25 sys.ps1
26 except AttributeError:
27 sys.ps1 = '>>> '
28 try:
29 sys.ps2
30 except AttributeError:
31 sys.ps2 = '... '
32
33 @expose()
35 more, output = self._process_request(line)
36 return dict(more=more, output=output)
37
38 @expose()
40 outlines = []
41
42 lines = [line for line in block.split('\n')]
43
44 for line in lines:
45 more, output = self._process_request(line)
46
47 if output[-1] == '\n':
48 output = output[:-1]
49
50 outlines.append(output)
51
52 return dict(more=more, output='\n'.join(outlines))
53
55 if len(self.console.buffer):
56 prompt = sys.ps2
57 else:
58 prompt = sys.ps1
59
60 myout = StringIO.StringIO()
61
62 output = "%s%s" % (prompt, line)
63
64
65 try:
66 sys.stdout = myout
67 sys.stderr = myout
68 more = self.console.push(line)
69 finally:
70 sys.stdout = sys.__stdout__
71 sys.stderr = sys.__stderr__
72
73 stdout = myout.getvalue()
74
75 if stdout:
76 output = '%s\n%s' % (output, stdout)
77
78 return more, output.rstrip()
79
81 data = dict()
82 locs = dict(__name__='tg-admin', __doc__=None,
83 reload_console=self.new_console)
84 try:
85 mod = turbogears.util.get_model()
86 if mod:
87 locs.update(mod.__dict__)
88 except (pkg_resources.DistributionNotFound, ImportError):
89 import traceback
90 error = "Error: could not load data model.\n"
91 data['errors'] = [error]
92 error += traceback.format_exc()
93 log.warn(error)
94 self.console = InteractiveConsole(locals=locs)
95 return data
96
97 @expose(template="turbogears.toolbox.console")
103