Search code examples
pythonpy2exe

ImportError: cannot import name chardet


Hi i have written a python scraper in which i am importing requests and Beautiful soup module . I am using python2.7 . I am crating Windows executable (.exe) from my Python script using py2exe module. For that i have created setup.py as following :

from distutils.core import setup
import py2exe
import requests

packages = [
    'requests',
    'requests.packages',
    'requests.packages.chardet',
    'requests.packages.urllib3',
    'requests.packages.urllib3.packages',
    'requests.packages.urllib3.contrib',
    'requests.packages.urllib3.util',
    'requests.packages.urllib3.packages.ssl_match_hostname',
]

setup(
    console=['CompanyScraper-1.6.py']
    )

I have created .exe file by running command "python setup.py py2exe". But while running the .exe file on window it throwing following error:

Traceback (most recent call last):
  File "CompanyScraper-1.6.py", line 13, in <module>
  File "requests\__init__.pyc", line 58, in <module>
  File "requests\utils.pyc", line 26, in <module>
  File "requests\compat.pyc", line 7, in <module>
ImportError: cannot import name chardet

i could not undaerstand why this chardet import error though i have included package into setup.py

Thanks you for looking into my issue.


Solution

  • As you can see from the traceback -

    Traceback (most recent call last):
      File "CompanyScraper-1.6.py", line 13, in <module>
      File "requests\__init__.pyc", line 58, in <module>
      File "requests\utils.pyc", line 26, in <module>
      File "requests\compat.pyc", line 7, in <module>
    ImportError: cannot import name chardet
    

    You have a requests directory with a __init__.py . This is masking the requests package from the library , so when you try to import chardet or any such thing from requests library , it tries to search for it in this local package, and not the library one.

    The best solution for this would be to rename the directory and your local package from requests to something else, so that the name does not conflict with any library packages.