@@ -109,10 +109,30 @@ def runsource(self, source, filename=None, symbol='single',
109109
110110 source, filename and symbol are passed on to
111111 code.InteractiveInterpreter.runsource. If encode is True, the source
112- will be encoded. On Python 3.X, encode will be ignored."""
113- if not py3 and encode :
114- source = u'# coding: %s\n \n %s' % (self .encoding , source )
115- source = source .encode (self .encoding )
112+ will be encoded. On Python 3.X, encode will be ignored.
113+
114+ encode doesn't encode the source, it just adds an encoding comment
115+ that specifies the encoding of the source.
116+ encode should only be used for interactive interpreter input,
117+ files should always have an encoding comment or be ASCII.
118+
119+ In Python 3, source must be a unicode string
120+ In Python 2, source may be latin-1 bytestring or unicode string,
121+ following the interface of code.InteractiveInterpreter"""
122+ if encode and not py3 :
123+ if isinstance (source , str ):
124+ # encoding only makes sense for bytestrings
125+ assert isinstance (source , str )
126+ source = b'# coding: %s\n \n %s' % (self .encoding , source )
127+ else :
128+ # 2 blank lines still need to be added because this
129+ # interpreter always adds 2 lines to stack trace line
130+ # numbers in Python 2
131+ comment = inspection .get_encoding_comment (source )
132+ if comment :
133+ source = source .replace (comment , u'%s\n \n ' % comment , 1 )
134+ else :
135+ source = u'\n \n ' + source
116136 if filename is None :
117137 filename = filename_for_console_input (source )
118138 with self .timer :
@@ -138,11 +158,11 @@ def showsyntaxerror(self, filename=None):
138158 pass
139159 else :
140160 # Stuff in the right filename and right lineno
141- if not py3 :
142- lineno -= 2
143161 # strip linecache line number
144162 if re .match (r'<bpython-input-\d+>' , filename ):
145163 filename = '<input>'
164+ if filename == '<input>' and not py3 :
165+ lineno -= 2
146166 value = SyntaxError (msg , (filename , lineno , offset , line ))
147167 sys .last_value = value
148168 list = traceback .format_exception_only (type , value )
@@ -166,8 +186,7 @@ def showtraceback(self):
166186 fname = '<input>'
167187 tblist [i ] = (fname , lineno , module , something )
168188 # Set the right lineno (encoding header adds an extra line)
169- if not py3 :
170- if fname == '<input>' :
189+ if fname == '<input>' and not py3 :
171190 tblist [i ] = (fname , lineno - 2 , module , something )
172191
173192 l = traceback .format_list (tblist )
0 commit comments