Repository navigation
Open
Description
Setup
I am reporting a problem wich works with Python 2.7 but fails with Python 3.6
Full details:
The sample script below works on a system where
import sys; print(sys.version)
print(sys.getdefaultencoding())
import platform; print(platform.python_implementation()); print(platform.platform())
import Bio; print(Bio.__version__)(note that I added a line with the default encoding), returns
2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]
ascii
CPython
Windows-7-6.1.7601-SP1
1.67
but fails on a system with:
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
utf-8
CPython
Windows-10-10.0.16299-SP0
1.69
Expected behaviour
The script:
from Bio import Entrez
Entrez.email = '[email protected]'
handle = Entrez.efetch(db="gds", id='200079209')
print(handle.read())
returns on the system with Python 2.7:
1. Airway epithelial cells from smokers with and without bronchial premalignant lesions
(Submitter supplied) While lung cancer is the leading cause of cancer death in the US, we have a limited understanding of the earliest molecular events preceding the onset of disease. Prior work has demonstrated that cigarette smoke creates a molecular “field of injury” throughout the airway epithelium and that there are distinct alterations in the airway transcriptome among smokers who have lung cancer. Molecular characterization of this airway “field of injury” in current and former smokers with premalignant lesions (PMLs) could provide novel insights into the earliest molecular events associated with lung carcinogenesis and identify relatively accessible biomarkers to guide lung cancer detection and early intervention. more...
Organism: Homo sapiens
Type: Expression profiling by high throughput sequencing
Platform: GPL16791 82 Samples
FTP download: GEO (TSV) ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE79nnn/GSE79209/
SRA Run Selector: https://www.ncbi.nlm.nih.gov/Traces/study/?acc=PRJNA315161
Series Accession: GSE79209 ID: 200079209
Actual behaviour
But on the system with Python 3.6, it returns:
Traceback (most recent call last):
File "c:/Users/jeroen/Documents/Code Snippets/Python/BioPython/unicode_bug.py", line 11, in <module>
print(handle.read())
File "C:\Users\jeroen\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 362: character maps to <undefined>
Steps to reproduce
The problem seems to be that Python 3.6 tries to decode the handle with encoding cp1252.
The character at position 362 that seems to be causing the error is the closing quote at the end of “field of injury”. When I do print handle.read()[362] on the system with Python 2.7 I get: ン.
Also see this stackoverflow question for a related problem.
Reacted by dterg and Michael Sanford
Metadata
Metadata
Assignees
Labels
No labels
Activity
peterjc commentedon Oct 6, 2017
I've never seen any clear documentation from the NCBI on what encoding they use, and it is most unfortunate when they use non UTF8 characters. That said, the example works for me which suggests closer examination of the locale settings and these fancy quote characters...
You may need to report this to the NCBI...
See also #1361 where some invalid characters had entered the GenBank database, but there at least the NCBI is reasonably clear that the GenBank files should be plain ASCII only.
peterjc commentedon Oct 6, 2017
This reproduces it - definitely something about the locale settings:
BioGeek commentedon Oct 8, 2017
Logged with NCBI via https://support.ncbi.nlm.nih.gov.
Their reference #28045-267686.
BioGeek commentedon Oct 11, 2017
The reply from NCBI was:
Not sure what I should reply, because I don't know how to reproduce the issue using
efetchfrom NCBI itself. The E-utilities are available for UNIX and Mac environments, but since I was having the problem on Windows 10, I installedentrez-directviacondaon the Windows Subsystem for Linux.There the command returns a UTF-8:
peterjc commentedon Oct 11, 2017
You would ideally have sent the NCBI a tool neutral test case, to do that first you'd need the Entrez URL:
More generally, you can remove the tool and email and it gives a minimal working URL - note you must quote the URL to prevent bash doing magic with the ampersands:
If you save that, or pipe it directly though hexdump, we can examine the problem characters:
You can see the opening quote of "field of injury" is three bytes in hex 0xE2 0x80 0x9C, matching Unicode Character 'LEFT DOUBLE QUOTATION MARK' (U+201C) http://www.fileformat.info/info/unicode/char/201c/index.htm
Likewise, the closing quote in the file is three bytes 0xE2 0x80 0x9D, matching Unicode Character 'RIGHT DOUBLE QUOTATION MARK' (U+201D) http://www.fileformat.info/info/unicode/char/201d/index.htm
This seems to be valid UTF8 (which would be a sensible encoding for the NCBI to be using even though I'm unaware they have declared this), e.g.
So, I think the NCBI are at fault for using non-ASCI without clearly declaring an encoding, but since their data here is UTF-8 it shouldn't be a big problem.
However, I believe the problem is in your machine locale settings. A related test:
Returning to the data from the NCBI, on my Linux machine if I deliberately use a non-UTF8 locale it breaks:
Here my Linux machine's locale is as follows:
What is the default locale/encoding on your machine? I'm not sure how best to find this on Windows - but perhaps the Windows Subsystem for Linux will let you run the
localecommand?dterg commentedon Oct 24, 2017
Same issue here on Win10. Locale are set as @peterjc reported.
peterjc commentedon Oct 24, 2017
@dterg how do you check the locale settings on Win10? And can you post that output please
dterg commentedon Oct 25, 2017
@peterjc Assuming you have bash for windows installed (as instructed here), then you can run any linux commands; in this case
locale. This is my output:As @BioGeek reported, everything works fine with python 2.7 so I have temporarily switch to 2.7. I attempted to explicitly define the encoding to utf-8 during the url handle instanstiation but that's not possible at the moment. Maybe that could be a possible solution?
peterjc commentedon Oct 25, 2017
@dterg Are you running Python via bash for Windows (in which case those locale settings are probably being used), or native Windows Python (in which case the locale settings may differ)?
Does this tell you anything useful (here running on my work Mac):
BioGeek commentedon Oct 26, 2017
OK, so let's recapitulate my experiments:
I'll show the output of
and whether or not the sample script from the first post succeeded.
Windows 7, Python 2.7.11
✔️ script succeeded
Windows 7, Python 3.5.1
❌ UnicodeDecodeError
Windows 10, Anaconda Python 3.6.3
❌ UnicodeDecodeError
Windows 10, Linux subsystem for Windows, Anaconda Python 3.6.3
✔️ script succeeded
So it seems that the combination of Pyhon >= 3.5.1 and a locale of
cp1252causes theUnicodeDecodeError.Let me know if I need to run additional tests.
peterjc commentedon Oct 26, 2017
Great - so the answer seems to be ensure you are using a UTF-8 locale to work with NCBI data from Entrez (or stick with Python 2 which doesn't care).
Assuming the NCBI were to officially state that Entrez returns data encoded as UTF-8, is there anything we can change in
Bio.Entrezto work better on locales likecp1252orC?dterg commentedon Oct 26, 2017
In my case on Windows 10, Anaconda Python 3.5.4 this is the output:
('en_US', 'cp1252') ('None, None) cp1252Checking the systems default encoding:
outputs
utf-8Given that locale.getdefaultlocale() outputted
cp1252, the below fixes it for me (i.e. now I can run the script on Win 10, python 3.5):Does it fix it for you @BioGeek?
dterg commentedon Oct 26, 2017
@peterjc Maybe an internal check on the encoding of the handle to see if its anything other than utf8 and internally set the locale to utf8 might be more user-friendly?
peterjc commentedon Oct 26, 2017
@dterg can you explore that idea? I do not currently have access to a Windows machine for direct testing.
We may need to document setting the locale to UTF-8 for Python 3 Windows users.
I also think we should follow up with the NCBI, as they should either fix the funny quotes in this example, or document what encoding they are using.
BioGeek commentedon Oct 26, 2017
@dterg Unfortunately, your fix doesn't work for me:
prints (when run with Anaconda Python 3.6.3 on Windows 10):
So, despite the monkeypatching, it still is going into the
lib\encodings\cp1252.pyfile.I'll follow up with the NCBI to get a definite answer about the encoding they are using.
BioGeek commentedon Oct 26, 2017
Response from NCBI:
peterjc commentedon Oct 26, 2017
They're right that the XML formats will often declare an encoding, as here:
The problem is the plain text output - where I appreciate that Entrez is sitting on top of a range of back end systems with different limitations. One option is they could commit to only return ASCII, but otherwise it certainly seems assuming UTF-8 from Entrez is a reasonable stance.
peterjc commentedon Oct 27, 2017
In pull request #1429 @BioGeek is taking advantage of the HTTP headers to see which encoding the NCBI Entrez (or other web-services) say they are using. I would still welcome a human readable statement in the Entrez help about the encoding, but this is a practical way forward.
Determine encoding for urllib handles from HTTP headers
Determine encoding for urllib handles from HTTP headers
danablanc commentedon Dec 17, 2017
Hi!
I have the same problem when I invoke the read function.
How can I deal with this issue?
Thank you!
BioGeek commentedon Dec 17, 2017
Hi @danablanc,
You can manually apply these changes to the file
Bio/_py3k/__init__.py.Can you confirm that this solves your issue?
danablanc commentedon Dec 17, 2017
@BioGeek thank you! My issue was solved
PraxisSpace commentedon Feb 15, 2018
The latest commit still can result in crashes on Windows with python3.
For example, the following URL, generated from an NCBI request, returns an xml file:
https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=protein&id=71042798%2C157833493%2C371927696%2C157834149%2C386783435%2C390981250%2C848130061%2C99031714%2C40889881%2C835020732%2C119390124%2C308198780%2C157833610%2C161172175%2C2781023%2C47169448%2C315583375%2C294662290%2C319443304%2C700588158%2C193506632%2C330689316%2C294662288%2C550545872%2C1321390714%2C1285033580%2C700588159%2C1321390705%2C22219037%2C13399644%2C584579595%2C343197194%2C317455537%2C344189571%2C34810932%2C444302159%2C334878440%2C560189139%2C560189134%2C196049869%2C576865086%2C576865080%2C256032553%2C1942184%2C1272615640%2C157831581%2C157830096%2C806394422%2C1272615642%2C1023176681&retmode=xml&The XML does not indicate its encoding.
The query for default encoding, done here, can return
Nonewithout a user's preferred encoding having previously been set. Withencoding=None, the call toio.TextIOWrapper(io.BufferedReader(handle), encoding=encoding)gets you back to the system's default encoding, which on windows iscp1252which brings you back to square one.But regardless, the logic behind calling
locale.getpreferredencoding(False)seems a little worrisome.The user's default encoding would seem to be irrelevant. It is only the encoding of the remote resource that matters, and there, a default of 'UTF-8' seems the safest.
Any thoughts then on changing this line to be simply:
encoding = 'UTF-8'peterjc commentedon Feb 15, 2018
@EdwardBlakeMiller Please report to the NCBI that with
db=proteinandretmode=xmlyou are getting back an XML file which does not declare its encoding.But good to know that in this example too, defaulting to UTF-8 works.
PraxisSpace commentedon Feb 15, 2018
Hi, @peterjc. Is there a submission form to use to report this to the NCBI?
peterjc commentedon Feb 15, 2018
I don't think there is a contact form, try the
eutilitiesatncbi.nlm.nih.govaddress? You can CC my GoogleMail address if you like.mdehoon commentedon Nov 10, 2020
If I understand correctly, Entrez uses UTF-8, which with the current version of BIopython is decoded correctly in the
Entrez._openfunction called byEntrez.efetch. The problem only happens if you try to print the resulting string to screen, as the string contains unicode characters that the terminal (depending on the locale settings) does not know how to handle. But this issue is independent of NCBI Entrez and Biopython; you would not be able to print any other string containing those unicode characters to the terminal either.If my understanding is correct, can we close this issue?