comparison code.py @ 183:7b6aba7839ea

getGameEnvironment of GameState now returns a locals dictionary that is empty at the beginning of the game and will be saved in save games. The vals and funcs are now both in the globals dictionary. This WILL break old saves.
author Beliar <KarstenBock@gmx.net>
date Thu, 15 Mar 2012 16:24:05 +0100
parents
children
comparison
equal deleted inserted replaced
182:f131a1b01254 183:7b6aba7839ea
1 """Utilities needed to emulate Python's interactive interpreter with changes for PARPG
2 The original code module is part of pythons standard modules.
3 """
4
5 # Inspired by similar code by Jeff Epler and Fredrik Lundh.
6
7 # Changed for PARPG to also accept a globals argument
8
9 import sys
10 import traceback
11 from codeop import CommandCompiler, compile_command
12
13 __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
14 "compile_command"]
15
16 def softspace(file, newvalue):
17 oldvalue = 0
18 try:
19 oldvalue = file.softspace
20 except AttributeError:
21 pass
22 try:
23 file.softspace = newvalue
24 except (AttributeError, TypeError):
25 # "attribute-less object" or "read-only attributes"
26 pass
27 return oldvalue
28
29 class InteractiveInterpreter:
30 """Base class for InteractiveConsole.
31
32 This class deals with parsing and interpreter state (the user's
33 namespace); it doesn't deal with input buffering or prompting or
34 input file naming (the filename is always passed in explicitly).
35
36 """
37
38 def __init__(self, globals=None, locals=None ):
39 """Constructor.
40
41 The optional 'globals' and 'locals' arguments specify the dictionary in
42 which code will be executed; globals defaults to a newly created
43 dictionary with key "__name__" set to "__console__" and key
44 "__doc__" set to None.
45
46 """
47 if globals is None:
48 globals = {"__name__": "__console__", "__doc__": None}
49 self.locals = locals
50 self.globals = globals
51 self.compile = CommandCompiler()
52
53 def runsource(self, source, filename="<input>", symbol="single"):
54 """Compile and run some source in the interpreter.
55
56 Arguments are as for compile_command().
57
58 One several things can happen:
59
60 1) The input is incorrect; compile_command() raised an
61 exception (SyntaxError or OverflowError). A syntax traceback
62 will be printed by calling the showsyntaxerror() method.
63
64 2) The input is incomplete, and more input is required;
65 compile_command() returned None. Nothing happens.
66
67 3) The input is complete; compile_command() returned a code
68 object. The code is executed by calling self.runcode() (which
69 also handles run-time exceptions, except for SystemExit).
70
71 The return value is True in case 2, False in the other cases (unless
72 an exception is raised). The return value can be used to
73 decide whether to use sys.ps1 or sys.ps2 to prompt the next
74 line.
75
76 """
77 try:
78 code = self.compile(source, filename, symbol)
79 except (OverflowError, SyntaxError, ValueError):
80 # Case 1
81 self.showsyntaxerror(filename)
82 return False
83
84 if code is None:
85 # Case 2
86 return True
87
88 # Case 3
89 self.runcode(code)
90 return False
91
92 def runcode(self, code):
93 """Execute a code object.
94
95 When an exception occurs, self.showtraceback() is called to
96 display a traceback. All exceptions are caught except
97 SystemExit, which is reraised.
98
99 A note about KeyboardInterrupt: this exception may occur
100 elsewhere in this code, and may not always be caught. The
101 caller should be prepared to deal with it.
102
103 """
104 try:
105 exec code in self.globals, self.locals
106 except SystemExit:
107 raise
108 except:
109 self.showtraceback()
110 else:
111 if softspace(sys.stdout, 0):
112 print
113
114 def showsyntaxerror(self, filename=None):
115 """Display the syntax error that just occurred.
116
117 This doesn't display a stack trace because there isn't one.
118
119 If a filename is given, it is stuffed in the exception instead
120 of what was there before (because Python's parser always uses
121 "<string>" when reading from a string).
122
123 The output is written by self.write(), below.
124
125 """
126 type, value, sys.last_traceback = sys.exc_info()
127 sys.last_type = type
128 sys.last_value = value
129 if filename and type is SyntaxError:
130 # Work hard to stuff the correct filename in the exception
131 try:
132 msg, (dummy_filename, lineno, offset, line) = value
133 except:
134 # Not the format we expect; leave it alone
135 pass
136 else:
137 # Stuff in the right filename
138 value = SyntaxError(msg, (filename, lineno, offset, line))
139 sys.last_value = value
140 list = traceback.format_exception_only(type, value)
141 map(self.write, list)
142
143 def showtraceback(self):
144 """Display the exception that just occurred.
145
146 We remove the first stack item because it is our own code.
147
148 The output is written by self.write(), below.
149
150 """
151 try:
152 type, value, tb = sys.exc_info()
153 sys.last_type = type
154 sys.last_value = value
155 sys.last_traceback = tb
156 tblist = traceback.extract_tb(tb)
157 del tblist[:1]
158 list = traceback.format_list(tblist)
159 if list:
160 list.insert(0, "Traceback (most recent call last):\n")
161 list[len(list):] = traceback.format_exception_only(type, value)
162 finally:
163 tblist = tb = None
164 map(self.write, list)
165
166 def write(self, data):
167 """Write a string.
168
169 The base implementation writes to sys.stderr; a subclass may
170 replace this with a different implementation.
171
172 """
173 sys.stderr.write(data)
174
175
176 class InteractiveConsole(InteractiveInterpreter):
177 """Closely emulate the behavior of the interactive Python interpreter.
178
179 This class builds on InteractiveInterpreter and adds prompting
180 using the familiar sys.ps1 and sys.ps2, and input buffering.
181
182 """
183
184 def __init__(self, globals=None, locals=None, filename="<console>"):
185 """Constructor.
186
187 The optional locals and globals argument swill be passed to the
188 InteractiveInterpreter base class.
189
190 The optional filename argument should specify the (file)name
191 of the input stream; it will show up in tracebacks.
192
193 """
194 InteractiveInterpreter.__init__(self, globals, locals)
195 self.filename = filename
196 self.resetbuffer()
197
198 def resetbuffer(self):
199 """Reset the input buffer."""
200 self.buffer = []
201
202 def interact(self, banner=None):
203 """Closely emulate the interactive Python console.
204
205 The optional banner argument specify the banner to print
206 before the first interaction; by default it prints a banner
207 similar to the one printed by the real Python interpreter,
208 followed by the current class name in parentheses (so as not
209 to confuse this with the real interpreter -- since it's so
210 close!).
211
212 """
213 try:
214 sys.ps1
215 except AttributeError:
216 sys.ps1 = ">>> "
217 try:
218 sys.ps2
219 except AttributeError:
220 sys.ps2 = "... "
221 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
222 if banner is None:
223 self.write("Python %s on %s\n%s\n(%s)\n" %
224 (sys.version, sys.platform, cprt,
225 self.__class__.__name__))
226 else:
227 self.write("%s\n" % str(banner))
228 more = 0
229 while 1:
230 try:
231 if more:
232 prompt = sys.ps2
233 else:
234 prompt = sys.ps1
235 try:
236 line = self.raw_input(prompt)
237 # Can be None if sys.stdin was redefined
238 encoding = getattr(sys.stdin, "encoding", None)
239 if encoding and not isinstance(line, unicode):
240 line = line.decode(encoding)
241 except EOFError:
242 self.write("\n")
243 break
244 else:
245 more = self.push(line)
246 except KeyboardInterrupt:
247 self.write("\nKeyboardInterrupt\n")
248 self.resetbuffer()
249 more = 0
250
251 def push(self, line):
252 """Push a line to the interpreter.
253
254 The line should not have a trailing newline; it may have
255 internal newlines. The line is appended to a buffer and the
256 interpreter's runsource() method is called with the
257 concatenated contents of the buffer as source. If this
258 indicates that the command was executed or invalid, the buffer
259 is reset; otherwise, the command is incomplete, and the buffer
260 is left as it was after the line was appended. The return
261 value is 1 if more input is required, 0 if the line was dealt
262 with in some way (this is the same as runsource()).
263
264 """
265 self.buffer.append(line)
266 source = "\n".join(self.buffer)
267 more = self.runsource(source, self.filename)
268 if not more:
269 self.resetbuffer()
270 return more
271
272 def raw_input(self, prompt=""):
273 """Write a prompt and read a line.
274
275 The returned line does not include the trailing newline.
276 When the user enters the EOF key sequence, EOFError is raised.
277
278 The base implementation uses the built-in function
279 raw_input(); a subclass may replace this with a different
280 implementation.
281
282 """
283 return raw_input(prompt)