diff options
author | Ned Batchelder <ned@nedbatchelder.com> | 2011-08-28 15:05:45 -0400 |
---|---|---|
committer | Ned Batchelder <ned@nedbatchelder.com> | 2011-08-28 15:05:45 -0400 |
commit | 8ade83f4e58cda85312fa05255289eefcf62767b (patch) | |
tree | 0b7c9e0fa467eda762c947f97bb189ea688090fd /coverage/backward.py | |
parent | 4a516e994668c85c5f4dd8dd785f70a07ea01293 (diff) | |
download | python-coveragepy-8ade83f4e58cda85312fa05255289eefcf62767b.tar.gz |
Add another way to open source files, that works on 3.1
Diffstat (limited to 'coverage/backward.py')
-rw-r--r-- | coverage/backward.py | 24 |
1 files changed, 20 insertions, 4 deletions
diff --git a/coverage/backward.py b/coverage/backward.py index 31668e7..ef2a774 100644 --- a/coverage/backward.py +++ b/coverage/backward.py @@ -73,13 +73,29 @@ except ImportError: import ConfigParser as configparser # Python 3.2 provides `tokenize.open`, the best way to open source files. +import tokenize try: - import tokenize open_source = tokenize.open # pylint: disable=E1101 except AttributeError: - def open_source(fname): - """Open a source file the best way.""" - return open(fname, "rU") + try: + detect_encoding = tokenize.detect_encoding + except AttributeError: + def open_source(fname): + """Open a source file the best way.""" + return open(fname, "rU") + else: + from io import TextIOWrapper + # Copied from the 3.2 stdlib: + def open_source(fname): + """Open a file in read only mode using the encoding detected by + detect_encoding(). + """ + buffer = open(fname, 'rb') + encoding, lines = detect_encoding(buffer.readline) + buffer.seek(0) + text = TextIOWrapper(buffer, encoding, line_buffering=True) + text.mode = 'r' + return text # Python 3.x is picky about bytes and strings, so provide methods to # get them right, and make them no-ops in 2.x |