21
21
PY3 = sys .version_info [0 ] == 3
22
22
23
23
def exec_code (code , env , kernel ):
24
+ import traceback
24
25
try :
25
- exec (code , env )
26
+ ccode = compile (code , "python cell" , "exec" )
26
27
except Exception as exc :
27
- import traceback
28
28
ex_type , ex , tb = sys .exc_info ()
29
- return ExceptionWrapper (ex_type .__name__ , repr (exc .args ), traceback .format_tb (tb ))
29
+ tb_format = ["%s: %s" % (ex .__class__ .__name__ , str (ex ))]
30
+ return ExceptionWrapper (ex_type .__name__ , repr (exc .args ), tb_format )
31
+ try :
32
+ exec (ccode , env )
33
+ except Exception as exc :
34
+ ex_type , ex , tb = sys .exc_info ()
35
+ line1 = ["Traceback (most recent call last):" ]
36
+ line2 = ["%s: %s" % (ex .__class__ .__name__ , str (ex ))]
37
+ tb_format = line1 + [line .rstrip () for line in traceback .format_tb (tb )[1 :]] + line2
38
+ return ExceptionWrapper (ex_type .__name__ , repr (exc .args ), tb_format )
30
39
if "retval" in env :
31
40
return env ["retval" ]
32
41
@@ -44,7 +53,7 @@ def line_python(self, *args):
44
53
This line magic will evaluate the CODE (either expression or
45
54
statement) as Python code.
46
55
47
- Note that the version of Python is that of the notebook server.
56
+ Note that the version of Python is that of the notebook server.
48
57
49
58
Examples:
50
59
%python x = 42
@@ -93,16 +102,16 @@ def cell_python(self, eval_output=False):
93
102
variable "retval".
94
103
95
104
The -e or --eval_output flag signals that the retval value expression
96
- will be used as code for the cell to be evaluated by the host
105
+ will be used as code for the cell to be evaluated by the host
97
106
language.
98
107
99
- Note that the version of Python is that of the notebook server.
108
+ Note that the version of Python is that of the notebook server.
100
109
101
110
Examples:
102
- %%python
111
+ %%python
103
112
x = 42
104
113
105
- %%python
114
+ %%python
106
115
import math
107
116
retval = x + math.pi
108
117
@@ -116,7 +125,7 @@ def cell_python(self, eval_output=False):
116
125
if self .code .strip ():
117
126
if eval_output :
118
127
self .eval (self .code )
119
- self .code = str (self .env ["retval" ]) if ("retval" in self .env and
128
+ self .code = str (self .env ["retval" ]) if ("retval" in self .env and
120
129
self .env ["retval" ] != None ) else ""
121
130
self .retval = None
122
131
self .env ["retval" ] = None
@@ -184,7 +193,7 @@ def get_help_on(self, info, level=0, none_on_fail=False):
184
193
185
194
if not obj :
186
195
return default
187
-
196
+
188
197
strhelp = pydoc .render_doc (obj , "Help on %s" )
189
198
if level == 0 :
190
199
return getattr (obj , '__doc__' , strhelp )
@@ -194,4 +203,3 @@ def get_help_on(self, info, level=0, none_on_fail=False):
194
203
195
204
def register_magics (kernel ):
196
205
kernel .register_magics (PythonMagic )
197
-
0 commit comments