~ubuntu-branches/debian/experimental/spyder/experimental

« back to all changes in this revision

Viewing changes to spyderlib/interpreter.py

  • Committer: Package Import Robot
  • Author(s): Picca Frédéric-Emmanuel
  • Date: 2013-01-20 12:19:54 UTC
  • mfrom: (1.1.16)
  • Revision ID: package-import@ubuntu.com-20130120121954-1jt1xa924bshhvh0
Tags: 2.2.0~beta1+dfsg-2
fix typo ipython-qtconsol -> ipython-qtconsole

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
#
3
 
# Copyright © 2009-2010 Pierre Raybaut
4
 
# Licensed under the terms of the MIT License
5
 
# (see spyderlib/__init__.py for details)
6
 
 
7
 
"""Shell Interpreter"""
8
 
 
9
 
import sys
10
 
import atexit
11
 
import threading
12
 
import ctypes
13
 
import os
14
 
import re
15
 
import os.path as osp
16
 
import pydoc
17
 
from subprocess import Popen, PIPE
18
 
from code import InteractiveConsole
19
 
 
20
 
# Local imports:
21
 
from spyderlib.utils.dochelpers import isdefined
22
 
from spyderlib.utils import encoding
23
 
 
24
 
# Force Python to search modules in the current directory first:
25
 
sys.path.insert(0, '')
26
 
 
27
 
 
28
 
def guess_filename(filename):
29
 
    """Guess filename"""
30
 
    if osp.isfile(filename):
31
 
        return filename
32
 
    if not filename.endswith('.py'):
33
 
        filename += '.py'
34
 
    for path in [os.getcwdu()]+sys.path:
35
 
        fname = osp.join(path, filename)
36
 
        if osp.isfile(fname):
37
 
            return fname
38
 
        elif osp.isfile(fname+'.py'):
39
 
            return fname+'.py'
40
 
        elif osp.isfile(fname+'.pyw'):
41
 
            return fname+'.pyw'
42
 
    return filename
43
 
 
44
 
class Interpreter(InteractiveConsole, threading.Thread):
45
 
    """Interpreter, executed in a separate thread"""
46
 
    p1 = ">>> "
47
 
    p2 = "... "
48
 
    def __init__(self, namespace=None, exitfunc=None,
49
 
                 Output=None, WidgetProxy=None, debug=False):
50
 
        """
51
 
        namespace: locals send to InteractiveConsole object
52
 
        commands: list of commands executed at startup
53
 
        """
54
 
        InteractiveConsole.__init__(self, namespace)
55
 
        threading.Thread.__init__(self)
56
 
        
57
 
        self._id = None
58
 
        
59
 
        self.exit_flag = False
60
 
        self.debug = debug
61
 
        
62
 
        # Execution Status
63
 
        self.more = False
64
 
        
65
 
        if exitfunc is not None:
66
 
            atexit.register(exitfunc)
67
 
        
68
 
        self.namespace = self.locals
69
 
        self.namespace['__name__'] = '__main__'
70
 
        self.namespace['execfile'] = self.execfile
71
 
        self.namespace['runfile'] = self.runfile
72
 
        self.namespace['raw_input'] = self.raw_input_replacement
73
 
        self.namespace['help'] = self.help_replacement
74
 
                    
75
 
        # Capture all interactive input/output 
76
 
        self.initial_stdout = sys.stdout
77
 
        self.initial_stderr = sys.stderr
78
 
        self.initial_stdin = sys.stdin
79
 
        
80
 
        # Create communication pipes
81
 
        pr, pw = os.pipe()
82
 
        self.stdin_read = os.fdopen(pr, "r")
83
 
        self.stdin_write = os.fdopen(pw, "w", 0)
84
 
        self.stdout_write = Output()
85
 
        self.stderr_write = Output()
86
 
        
87
 
        self.input_condition = threading.Condition()
88
 
        self.widget_proxy = WidgetProxy(self.input_condition)
89
 
        
90
 
        self.redirect_stds()
91
 
        
92
 
 
93
 
    #------ Standard input/output
94
 
    def redirect_stds(self):
95
 
        """Redirects stds"""
96
 
        if not self.debug:
97
 
            sys.stdout = self.stdout_write
98
 
            sys.stderr = self.stderr_write
99
 
            sys.stdin = self.stdin_read
100
 
        
101
 
    def restore_stds(self):
102
 
        """Restore stds"""
103
 
        if not self.debug:
104
 
            sys.stdout = self.initial_stdout
105
 
            sys.stderr = self.initial_stderr
106
 
            sys.stdin = self.initial_stdin
107
 
 
108
 
    def raw_input_replacement(self, prompt=''):
109
 
        """For raw_input builtin function emulation"""
110
 
        self.widget_proxy.wait_input(prompt)
111
 
        self.input_condition.acquire()
112
 
        while not self.widget_proxy.data_available():
113
 
            self.input_condition.wait()
114
 
        inp = self.widget_proxy.input_data
115
 
        self.input_condition.release()
116
 
        return inp
117
 
        
118
 
    def help_replacement(self, text=None, interactive=False):
119
 
        """For help builtin function emulation"""
120
 
        if text is not None and not interactive:
121
 
            return pydoc.help(text)
122
 
        elif text is None:
123
 
            pyver = "%d.%d" % (sys.version_info[0], sys.version_info[1])
124
 
            self.write("""
125
 
Welcome to Python %s!  This is the online help utility.
126
 
 
127
 
If this is your first time using Python, you should definitely check out
128
 
the tutorial on the Internet at http://www.python.org/doc/tut/.
129
 
 
130
 
Enter the name of any module, keyword, or topic to get help on writing
131
 
Python programs and using Python modules.  To quit this help utility and
132
 
return to the interpreter, just type "quit".
133
 
 
134
 
To get a list of available modules, keywords, or topics, type "modules",
135
 
"keywords", or "topics".  Each module also comes with a one-line summary
136
 
of what it does; to list the modules whose summaries contain a given word
137
 
such as "spam", type "modules spam".
138
 
""" % pyver)
139
 
        else:
140
 
            text = text.strip()
141
 
            try:
142
 
                eval("pydoc.help(%s)" % text)
143
 
            except (NameError, SyntaxError):
144
 
                print "no Python documentation found for '%r'" % text
145
 
        self.write(os.linesep)
146
 
        self.widget_proxy.new_prompt("help> ")
147
 
        inp = self.raw_input_replacement()
148
 
        if inp.strip():
149
 
            self.help_replacement(inp, interactive=True)
150
 
        else:
151
 
            self.write("""
152
 
You are now leaving help and returning to the Python interpreter.
153
 
If you want to ask for help on a particular object directly from the
154
 
interpreter, you can type "help(object)".  Executing "help('string')"
155
 
has the same effect as typing a particular string at the help> prompt.
156
 
""")
157
 
 
158
 
    def run_command(self, cmd, new_prompt=True):
159
 
        """Run command in interpreter"""
160
 
        if cmd == 'exit()':
161
 
            self.exit_flag = True
162
 
            self.write('\n')
163
 
            return
164
 
        # -- Special commands type I
165
 
        #    (transformed into commands executed in the interpreter)
166
 
        # ? command
167
 
        special_pattern = r"^%s (?:r\')?(?:u\')?\"?\'?([a-zA-Z0-9_\.]+)"
168
 
        run_match = re.match(special_pattern % 'run', cmd)
169
 
        help_match = re.match(r'^([a-zA-Z0-9_\.]+)\?$', cmd)
170
 
        cd_match = re.match(r"^\!cd \"?\'?([a-zA-Z0-9_ \.]+)", cmd)
171
 
        if help_match:
172
 
            cmd = 'help(%s)' % help_match.group(1)
173
 
        # run command
174
 
        elif run_match:
175
 
            filename = guess_filename(run_match.groups()[0])
176
 
            cmd = 'runfile(r"%s", args=None)' % filename
177
 
        # !cd system command
178
 
        elif cd_match:
179
 
            cmd = 'import os; os.chdir(r"%s")' % cd_match.groups()[0].strip()
180
 
        # -- End of Special commands type I
181
 
            
182
 
        # -- Special commands type II
183
 
        #    (don't need code execution in interpreter)
184
 
        xedit_match = re.match(special_pattern % 'xedit', cmd)
185
 
        edit_match = re.match(special_pattern % 'edit', cmd)
186
 
        clear_match = re.match(r"^clear ([a-zA-Z0-9_, ]+)", cmd)
187
 
        # (external) edit command
188
 
        if xedit_match:
189
 
            filename = guess_filename(xedit_match.groups()[0])
190
 
            self.widget_proxy.edit(filename, external_editor=True)
191
 
        # local edit command
192
 
        elif edit_match:
193
 
            filename = guess_filename(edit_match.groups()[0])
194
 
            if osp.isfile(filename):
195
 
                self.widget_proxy.edit(filename)
196
 
            else:
197
 
                self.stderr_write.write(
198
 
                                "No such file or directory: %s\n" % filename)
199
 
        # remove reference (equivalent to MATLAB's clear command)
200
 
        elif clear_match:
201
 
            varnames = clear_match.groups()[0].replace(' ', '').split(',')
202
 
            for varname in varnames:
203
 
                try:
204
 
                    self.namespace.pop(varname)
205
 
                except KeyError:
206
 
                    pass
207
 
        # Execute command
208
 
        elif cmd.startswith('!'):
209
 
            # System ! command
210
 
            pipe = Popen(cmd[1:], shell=True,
211
 
                         stdin=PIPE, stderr=PIPE, stdout=PIPE)
212
 
            txt_out = encoding.transcode( pipe.stdout.read() )
213
 
            txt_err = encoding.transcode( pipe.stderr.read().rstrip() )
214
 
            if txt_err:
215
 
                self.stderr_write.write(txt_err)
216
 
            if txt_out:
217
 
                self.stdout_write.write(txt_out)
218
 
            self.stdout_write.write('\n')
219
 
            self.more = False
220
 
        # -- End of Special commands type II
221
 
        else:
222
 
            # Command executed in the interpreter
223
 
#            self.widget_proxy.set_readonly(True)
224
 
            self.more = self.push(cmd)
225
 
#            self.widget_proxy.set_readonly(False)
226
 
        
227
 
        if new_prompt:
228
 
            self.widget_proxy.new_prompt(self.p2 if self.more else self.p1)
229
 
        if not self.more:
230
 
            self.resetbuffer()
231
 
        
232
 
    def run(self):
233
 
        """Wait for input and run it"""
234
 
        while not self.exit_flag:
235
 
            self.run_line()
236
 
            
237
 
    def run_line(self):
238
 
        line = self.stdin_read.readline()
239
 
        if self.exit_flag:
240
 
            return
241
 
        # Remove last character which is always '\n':
242
 
        self.run_command(line[:-1])
243
 
        
244
 
    def get_thread_id(self):
245
 
        """Return thread id"""
246
 
        if self._id is None:
247
 
            for thread_id, obj in threading._active.items():
248
 
                if obj is self:
249
 
                    self._id = thread_id
250
 
        return self._id
251
 
        
252
 
    def raise_keyboard_interrupt(self):
253
 
        if self.isAlive():
254
 
            ctypes.pythonapi.PyThreadState_SetAsyncExc(self.get_thread_id(),
255
 
                                           ctypes.py_object(KeyboardInterrupt))
256
 
            return True
257
 
        else:
258
 
            return False
259
 
            
260
 
            
261
 
    def closing(self):
262
 
        """Actions to be done before restarting this interpreter"""
263
 
        pass
264
 
        
265
 
    def execfile(self, filename):
266
 
        """Exec filename"""
267
 
        source = open(filename, 'r').read()
268
 
        try:
269
 
            try:
270
 
                name = filename.encode('ascii')
271
 
            except UnicodeEncodeError:
272
 
                name = '<executed_script>'
273
 
            code = compile(source, name, "exec")
274
 
        except (OverflowError, SyntaxError):
275
 
            InteractiveConsole.showsyntaxerror(self, filename)
276
 
        else:
277
 
            self.runcode(code)
278
 
        
279
 
    def runfile(self, filename, args=None):
280
 
        """
281
 
        Run filename
282
 
        args: command line arguments (string)
283
 
        """
284
 
        if args is not None and not isinstance(args, basestring):
285
 
            raise TypeError("expected a character buffer object")
286
 
        self.namespace['__file__'] = filename
287
 
        sys.argv = [filename]
288
 
        if args is not None:
289
 
            for arg in args.split():
290
 
                sys.argv.append(arg)
291
 
        self.execfile(filename)
292
 
        sys.argv = ['']
293
 
        self.namespace.pop('__file__')
294
 
        
295
 
    def eval(self, text):
296
 
        """
297
 
        Evaluate text and return (obj, valid)
298
 
        where *obj* is the object represented by *text*
299
 
        and *valid* is True if object evaluation did not raise any exception
300
 
        """
301
 
        assert isinstance(text, (str, unicode))
302
 
        try:
303
 
            return eval(text, self.locals), True
304
 
        except:
305
 
            return None, False
306
 
        
307
 
    def is_defined(self, objtxt, force_import=False):
308
 
        """Return True if object is defined"""
309
 
        return isdefined(objtxt, force_import=force_import,
310
 
                         namespace=self.locals)
311
 
        
312
 
    #===========================================================================
313
 
    # InteractiveConsole API
314
 
    #===========================================================================
315
 
    def push(self, line):
316
 
        """
317
 
        Push a line of source text to the interpreter
318
 
        
319
 
        The line should not have a trailing newline; it may have internal 
320
 
        newlines. The line is appended to a buffer and the interpreter’s 
321
 
        runsource() method is called with the concatenated contents of the 
322
 
        buffer as source. If this indicates that the command was executed 
323
 
        or invalid, the buffer is reset; otherwise, the command is incomplete, 
324
 
        and the buffer is left as it was after the line was appended. 
325
 
        The return value is True if more input is required, False if the line 
326
 
        was dealt with in some way (this is the same as runsource()).
327
 
        """
328
 
        return InteractiveConsole.push(self, line)
329
 
        
330
 
    def resetbuffer(self):
331
 
        """Remove any unhandled source text from the input buffer"""
332
 
        InteractiveConsole.resetbuffer(self)
 
1
# -*- coding: utf-8 -*-
 
2
#
 
3
# Copyright © 2009-2010 Pierre Raybaut
 
4
# Licensed under the terms of the MIT License
 
5
# (see spyderlib/__init__.py for details)
 
6
 
 
7
"""Shell Interpreter"""
 
8
 
 
9
import sys
 
10
import atexit
 
11
import threading
 
12
import ctypes
 
13
import os
 
14
import re
 
15
import os.path as osp
 
16
import pydoc
 
17
from subprocess import Popen, PIPE
 
18
from code import InteractiveConsole
 
19
 
 
20
# Local imports:
 
21
from spyderlib.utils.dochelpers import isdefined
 
22
from spyderlib.utils import encoding
 
23
 
 
24
# Force Python to search modules in the current directory first:
 
25
sys.path.insert(0, '')
 
26
 
 
27
 
 
28
def guess_filename(filename):
 
29
    """Guess filename"""
 
30
    if osp.isfile(filename):
 
31
        return filename
 
32
    if not filename.endswith('.py'):
 
33
        filename += '.py'
 
34
    for path in [os.getcwdu()]+sys.path:
 
35
        fname = osp.join(path, filename)
 
36
        if osp.isfile(fname):
 
37
            return fname
 
38
        elif osp.isfile(fname+'.py'):
 
39
            return fname+'.py'
 
40
        elif osp.isfile(fname+'.pyw'):
 
41
            return fname+'.pyw'
 
42
    return filename
 
43
 
 
44
class Interpreter(InteractiveConsole, threading.Thread):
 
45
    """Interpreter, executed in a separate thread"""
 
46
    p1 = ">>> "
 
47
    p2 = "... "
 
48
    def __init__(self, namespace=None, exitfunc=None,
 
49
                 Output=None, WidgetProxy=None, debug=False):
 
50
        """
 
51
        namespace: locals send to InteractiveConsole object
 
52
        commands: list of commands executed at startup
 
53
        """
 
54
        InteractiveConsole.__init__(self, namespace)
 
55
        threading.Thread.__init__(self)
 
56
        
 
57
        self._id = None
 
58
        
 
59
        self.exit_flag = False
 
60
        self.debug = debug
 
61
        
 
62
        # Execution Status
 
63
        self.more = False
 
64
        
 
65
        if exitfunc is not None:
 
66
            atexit.register(exitfunc)
 
67
        
 
68
        self.namespace = self.locals
 
69
        self.namespace['__name__'] = '__main__'
 
70
        self.namespace['execfile'] = self.execfile
 
71
        self.namespace['runfile'] = self.runfile
 
72
        self.namespace['raw_input'] = self.raw_input_replacement
 
73
        self.namespace['help'] = self.help_replacement
 
74
                    
 
75
        # Capture all interactive input/output 
 
76
        self.initial_stdout = sys.stdout
 
77
        self.initial_stderr = sys.stderr
 
78
        self.initial_stdin = sys.stdin
 
79
        
 
80
        # Create communication pipes
 
81
        pr, pw = os.pipe()
 
82
        self.stdin_read = os.fdopen(pr, "r")
 
83
        self.stdin_write = os.fdopen(pw, "w", 0)
 
84
        self.stdout_write = Output()
 
85
        self.stderr_write = Output()
 
86
        
 
87
        self.input_condition = threading.Condition()
 
88
        self.widget_proxy = WidgetProxy(self.input_condition)
 
89
        
 
90
        self.redirect_stds()
 
91
        
 
92
 
 
93
    #------ Standard input/output
 
94
    def redirect_stds(self):
 
95
        """Redirects stds"""
 
96
        if not self.debug:
 
97
            sys.stdout = self.stdout_write
 
98
            sys.stderr = self.stderr_write
 
99
            sys.stdin = self.stdin_read
 
100
        
 
101
    def restore_stds(self):
 
102
        """Restore stds"""
 
103
        if not self.debug:
 
104
            sys.stdout = self.initial_stdout
 
105
            sys.stderr = self.initial_stderr
 
106
            sys.stdin = self.initial_stdin
 
107
 
 
108
    def raw_input_replacement(self, prompt=''):
 
109
        """For raw_input builtin function emulation"""
 
110
        self.widget_proxy.wait_input(prompt)
 
111
        self.input_condition.acquire()
 
112
        while not self.widget_proxy.data_available():
 
113
            self.input_condition.wait()
 
114
        inp = self.widget_proxy.input_data
 
115
        self.input_condition.release()
 
116
        return inp
 
117
        
 
118
    def help_replacement(self, text=None, interactive=False):
 
119
        """For help builtin function emulation"""
 
120
        if text is not None and not interactive:
 
121
            return pydoc.help(text)
 
122
        elif text is None:
 
123
            pyver = "%d.%d" % (sys.version_info[0], sys.version_info[1])
 
124
            self.write("""
 
125
Welcome to Python %s!  This is the online help utility.
 
126
 
 
127
If this is your first time using Python, you should definitely check out
 
128
the tutorial on the Internet at http://www.python.org/doc/tut/.
 
129
 
 
130
Enter the name of any module, keyword, or topic to get help on writing
 
131
Python programs and using Python modules.  To quit this help utility and
 
132
return to the interpreter, just type "quit".
 
133
 
 
134
To get a list of available modules, keywords, or topics, type "modules",
 
135
"keywords", or "topics".  Each module also comes with a one-line summary
 
136
of what it does; to list the modules whose summaries contain a given word
 
137
such as "spam", type "modules spam".
 
138
""" % pyver)
 
139
        else:
 
140
            text = text.strip()
 
141
            try:
 
142
                eval("pydoc.help(%s)" % text)
 
143
            except (NameError, SyntaxError):
 
144
                print "no Python documentation found for '%r'" % text
 
145
        self.write(os.linesep)
 
146
        self.widget_proxy.new_prompt("help> ")
 
147
        inp = self.raw_input_replacement()
 
148
        if inp.strip():
 
149
            self.help_replacement(inp, interactive=True)
 
150
        else:
 
151
            self.write("""
 
152
You are now leaving help and returning to the Python interpreter.
 
153
If you want to ask for help on a particular object directly from the
 
154
interpreter, you can type "help(object)".  Executing "help('string')"
 
155
has the same effect as typing a particular string at the help> prompt.
 
156
""")
 
157
 
 
158
    def run_command(self, cmd, new_prompt=True):
 
159
        """Run command in interpreter"""
 
160
        if cmd == 'exit()':
 
161
            self.exit_flag = True
 
162
            self.write('\n')
 
163
            return
 
164
        # -- Special commands type I
 
165
        #    (transformed into commands executed in the interpreter)
 
166
        # ? command
 
167
        special_pattern = r"^%s (?:r\')?(?:u\')?\"?\'?([a-zA-Z0-9_\.]+)"
 
168
        run_match = re.match(special_pattern % 'run', cmd)
 
169
        help_match = re.match(r'^([a-zA-Z0-9_\.]+)\?$', cmd)
 
170
        cd_match = re.match(r"^\!cd \"?\'?([a-zA-Z0-9_ \.]+)", cmd)
 
171
        if help_match:
 
172
            cmd = 'help(%s)' % help_match.group(1)
 
173
        # run command
 
174
        elif run_match:
 
175
            filename = guess_filename(run_match.groups()[0])
 
176
            cmd = 'runfile(r"%s", args=None)' % filename
 
177
        # !cd system command
 
178
        elif cd_match:
 
179
            cmd = 'import os; os.chdir(r"%s")' % cd_match.groups()[0].strip()
 
180
        # -- End of Special commands type I
 
181
            
 
182
        # -- Special commands type II
 
183
        #    (don't need code execution in interpreter)
 
184
        xedit_match = re.match(special_pattern % 'xedit', cmd)
 
185
        edit_match = re.match(special_pattern % 'edit', cmd)
 
186
        clear_match = re.match(r"^clear ([a-zA-Z0-9_, ]+)", cmd)
 
187
        # (external) edit command
 
188
        if xedit_match:
 
189
            filename = guess_filename(xedit_match.groups()[0])
 
190
            self.widget_proxy.edit(filename, external_editor=True)
 
191
        # local edit command
 
192
        elif edit_match:
 
193
            filename = guess_filename(edit_match.groups()[0])
 
194
            if osp.isfile(filename):
 
195
                self.widget_proxy.edit(filename)
 
196
            else:
 
197
                self.stderr_write.write(
 
198
                                "No such file or directory: %s\n" % filename)
 
199
        # remove reference (equivalent to MATLAB's clear command)
 
200
        elif clear_match:
 
201
            varnames = clear_match.groups()[0].replace(' ', '').split(',')
 
202
            for varname in varnames:
 
203
                try:
 
204
                    self.namespace.pop(varname)
 
205
                except KeyError:
 
206
                    pass
 
207
        # Execute command
 
208
        elif cmd.startswith('!'):
 
209
            # System ! command
 
210
            pipe = Popen(cmd[1:], shell=True,
 
211
                         stdin=PIPE, stderr=PIPE, stdout=PIPE)
 
212
            txt_out = encoding.transcode( pipe.stdout.read() )
 
213
            txt_err = encoding.transcode( pipe.stderr.read().rstrip() )
 
214
            if txt_err:
 
215
                self.stderr_write.write(txt_err)
 
216
            if txt_out:
 
217
                self.stdout_write.write(txt_out)
 
218
            self.stdout_write.write('\n')
 
219
            self.more = False
 
220
        # -- End of Special commands type II
 
221
        else:
 
222
            # Command executed in the interpreter
 
223
#            self.widget_proxy.set_readonly(True)
 
224
            self.more = self.push(cmd)
 
225
#            self.widget_proxy.set_readonly(False)
 
226
        
 
227
        if new_prompt:
 
228
            self.widget_proxy.new_prompt(self.p2 if self.more else self.p1)
 
229
        if not self.more:
 
230
            self.resetbuffer()
 
231
        
 
232
    def run(self):
 
233
        """Wait for input and run it"""
 
234
        while not self.exit_flag:
 
235
            self.run_line()
 
236
            
 
237
    def run_line(self):
 
238
        line = self.stdin_read.readline()
 
239
        if self.exit_flag:
 
240
            return
 
241
        # Remove last character which is always '\n':
 
242
        self.run_command(line[:-1])
 
243
        
 
244
    def get_thread_id(self):
 
245
        """Return thread id"""
 
246
        if self._id is None:
 
247
            for thread_id, obj in threading._active.items():
 
248
                if obj is self:
 
249
                    self._id = thread_id
 
250
        return self._id
 
251
        
 
252
    def raise_keyboard_interrupt(self):
 
253
        if self.isAlive():
 
254
            ctypes.pythonapi.PyThreadState_SetAsyncExc(self.get_thread_id(),
 
255
                                           ctypes.py_object(KeyboardInterrupt))
 
256
            return True
 
257
        else:
 
258
            return False
 
259
            
 
260
            
 
261
    def closing(self):
 
262
        """Actions to be done before restarting this interpreter"""
 
263
        pass
 
264
        
 
265
    def execfile(self, filename):
 
266
        """Exec filename"""
 
267
        source = open(filename, 'r').read()
 
268
        try:
 
269
            try:
 
270
                name = filename.encode('ascii')
 
271
            except UnicodeEncodeError:
 
272
                name = '<executed_script>'
 
273
            code = compile(source, name, "exec")
 
274
        except (OverflowError, SyntaxError):
 
275
            InteractiveConsole.showsyntaxerror(self, filename)
 
276
        else:
 
277
            self.runcode(code)
 
278
        
 
279
    def runfile(self, filename, args=None):
 
280
        """
 
281
        Run filename
 
282
        args: command line arguments (string)
 
283
        """
 
284
        if args is not None and not isinstance(args, basestring):
 
285
            raise TypeError("expected a character buffer object")
 
286
        self.namespace['__file__'] = filename
 
287
        sys.argv = [filename]
 
288
        if args is not None:
 
289
            for arg in args.split():
 
290
                sys.argv.append(arg)
 
291
        self.execfile(filename)
 
292
        sys.argv = ['']
 
293
        self.namespace.pop('__file__')
 
294
        
 
295
    def eval(self, text):
 
296
        """
 
297
        Evaluate text and return (obj, valid)
 
298
        where *obj* is the object represented by *text*
 
299
        and *valid* is True if object evaluation did not raise any exception
 
300
        """
 
301
        assert isinstance(text, (str, unicode))
 
302
        try:
 
303
            return eval(text, self.locals), True
 
304
        except:
 
305
            return None, False
 
306
        
 
307
    def is_defined(self, objtxt, force_import=False):
 
308
        """Return True if object is defined"""
 
309
        return isdefined(objtxt, force_import=force_import,
 
310
                         namespace=self.locals)
 
311
        
 
312
    #===========================================================================
 
313
    # InteractiveConsole API
 
314
    #===========================================================================
 
315
    def push(self, line):
 
316
        """
 
317
        Push a line of source text to the interpreter
 
318
        
 
319
        The line should not have a trailing newline; it may have internal 
 
320
        newlines. The line is appended to a buffer and the interpreter’s 
 
321
        runsource() method is called with the concatenated contents of the 
 
322
        buffer as source. If this indicates that the command was executed 
 
323
        or invalid, the buffer is reset; otherwise, the command is incomplete, 
 
324
        and the buffer is left as it was after the line was appended. 
 
325
        The return value is True if more input is required, False if the line 
 
326
        was dealt with in some way (this is the same as runsource()).
 
327
        """
 
328
        return InteractiveConsole.push(self, "#coding=utf-8\n" + line)
 
329
        
 
330
    def resetbuffer(self):
 
331
        """Remove any unhandled source text from the input buffer"""
 
332
        InteractiveConsole.resetbuffer(self)
333
333
        
 
 
b'\\ No newline at end of file'