Skip to content

Commit d0bc25d

Browse files
committed
Try to read encoding of PYTHONSTARTUP file first, and then read it with correct encoding
Signed-off-by: Sebastian Ramacher <sebastian+dev@ramacher.at>
1 parent e4c3d4d commit d0bc25d

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

bpython/inspection.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@
2424
from __future__ import with_statement
2525
import collections
2626
import inspect
27+
import io
2728
import keyword
2829
import pydoc
2930
import types
31+
from six.moves import range
3032

3133
from pygments.token import Token
3234

@@ -280,13 +282,25 @@ def is_callable(obj):
280282

281283

282284
def get_encoding(obj):
285+
"""Try to obtain encoding information of the source of an object."""
283286
for line in inspect.findsource(obj)[0][:2]:
284287
m = get_encoding_re.search(line)
285288
if m:
286289
return m.group(1)
287290
return 'ascii'
288291

289292

293+
def get_encoding_file(fname):
294+
"""Try to obtain encoding information from a Python source file."""
295+
with io.open(fname, 'rt', encoding='ascii', errors='ignore') as f:
296+
for unused in range(2):
297+
line = f.readline()
298+
match = get_encoding_re.search(line)
299+
if match:
300+
return match.group(1)
301+
return 'ascii'
302+
303+
290304
def get_source_unicode(obj):
291305
"""Returns a decoded source of object"""
292306
if py3:

bpython/repl.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import code
2525
import errno
2626
import inspect
27+
import io
2728
import os
2829
import pkgutil
2930
import pydoc
@@ -406,12 +407,9 @@ def startup(self):
406407
"""
407408
filename = os.environ.get('PYTHONSTARTUP')
408409
if filename:
409-
with open(filename, 'r') as f:
410-
if py3:
411-
self.interp.runsource(f.read(), filename, 'exec')
412-
else:
413-
self.interp.runsource(f.read(), filename, 'exec',
414-
encode=False)
410+
encoding = inspection.get_encoding_file(filename)
411+
with io.open(filename, 'rt', encoding=encoding) as f:
412+
self.interp.runsource(f.read(), filename, 'exec')
415413

416414
def current_string(self, concatenate=False):
417415
"""If the line ends in a string get it, otherwise return ''"""

0 commit comments

Comments
 (0)