No module named encodings python windows

I'm installing Python on my Windows 10 laptop, and when I try to run it I get this: Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named '

I’m installing Python on my Windows 10 laptop, and when I try to run it I get this:

Fatal Python error: Py_Initialize: unable to load the file system
codec ModuleNotFoundError: No module named ‘encodings’ Current thread
0x0000037c (most recent call first):

Peter Mortensen's user avatar

asked Feb 28, 2017 at 15:32

Milos Milunovic's user avatar

Milos MilunovicMilos Milunovic

4022 gold badges5 silver badges10 bronze badges

I ran into this same issue on Windows 10. Here’s how I fixed it:

  1. Open your ‘Environment Variables‘ (Under ‘System Properties‘).
  2. In the window that opens, select the ‘Path‘ row, then click the ‘Edit…‘ button.
  3. There should be two environment variables C:Python37-32Scripts and C:Python37-32 Then click ‘OK‘ (Make sure to check that these path values correspond to the location and version of your Python install.)
  4. Next, in the top portion of the ‘Environment Variables‘ window, look for the PYTHONHOME variable and make sure that it is also set to C:Python37-32

answered Aug 18, 2018 at 18:44

J.S. Peterson's user avatar

4

This issue has been addressed here in this thread. Apparently, running the Python setup as an administrator and/or correctly setting the environment variables solved this issue.

Peter Mortensen's user avatar

answered Feb 28, 2017 at 15:44

Paandittya's user avatar

PaandittyaPaandittya

8358 silver badges17 bronze badges

4

First, don’t forget to select «Add Python 3.x to PATH» before you click on Install now and reboot after installation so that the new path is taken into account by Windows.

Second, I had the the same problem with Python 3 on Windows 7 and 64-bit and I got rid of it by deleting PYTHONPATH and PYTHONHOME from Windows 7 system environment variables, because I had a previous installation of Python 2 and those paths were pointing to my the Python 2 directory. I had to simply to delete the PYTHONPATH and PYTHONHOME variables.

Peter Mortensen's user avatar

answered Aug 6, 2017 at 20:03

Gorgorlu's user avatar

I had the same problem (I use a Mac, but I don’t think it makes any difference in this problem) and it was coming from the difference between the selected Python interpreter path and the current working directory in spyder.

I use virtual environments in Python to avoid version conflicts of installed modules between various projects (I believe it is a good practice). This leads me to configure the interpreter path in spyder by accessing:

preferences > python interpreter > use the following interpreter

The problem comes when I launch spyder from a different path. I get exactly the same error as Milo’s. To solve it I see two options:

  1. change the interpreter path to match the spyder working directory
  2. change the spyder working directory to match the Python interpreter path

Peter Mortensen's user avatar

answered Nov 21, 2019 at 11:52

David's user avatar

DavidDavid

392 bronze badges

I solved this issue by deleting my virtual environment and creating a new one. I believe in my case the error came because the old virtual environment was running on Python 3.6, which I had recently uninstalled and replaced with Python 3.8.

This is probably bad practice in general, but I don’t have any real projects where the version matters.

Peter Mortensen's user avatar

answered Aug 1, 2020 at 16:17

rocksNwaves's user avatar

rocksNwavesrocksNwaves

4,8203 gold badges31 silver badges66 bronze badges

2

Even I had the same issue when I installed the Python 3.7 beta version, and I resolved it by following these steps:

  1. If you have nay previous version of Python installed and the environment variable and path is set for that version already, just remove the path and environment variable

  2. Run the downloaded Python 3.7 EXE file file as administrator

  3. At the end of installation if it asks the permission for path length just click on that. Now type «python» on the command line and see. It should work.

Peter Mortensen's user avatar

answered May 8, 2018 at 8:49

pujitha's user avatar

I am not sure why this question is still here without a solution. I just encountered this and solved by this:

  1. Close all CMD or console emulators.

  2. Go to the system environment settings and clear all old Python path or environment settings. Make sure you check the PATH in both User and System settings as well.

  3. Try again python -V and see if you can run it or not.

  • If you have removed all Python environment settings, I recommend you to reinstall Python and turn on the Add Python to PATH setting during installation.

Peter Mortensen's user avatar

answered Jun 15, 2018 at 11:05

DrKNa's user avatar

DrKNaDrKNa

551 silver badge8 bronze badges

Before installing the Python interpreter, check environment and remove the existing PYTHONHOME, and python path under «PATH» of environment. Or change it to the new path to be installed.

Peter Mortensen's user avatar

answered Apr 13, 2020 at 2:33

caot's user avatar

caotcaot

2,87631 silver badges35 bronze badges

If this issue is happening to you in a virtual environment, just delete it and create another. It worked for me.

answered May 16, 2021 at 17:33

justbecause's user avatar

justbecausejustbecause

1692 silver badges8 bronze badges

I recently reinstalled ubuntu and did upgrade to 16.04 and cannot use python:

$ python manage.py runserver
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

At this point, python itself doesn’t work

$ python
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

Even this suggestion is no longer working:

unset PYTHONHOME
unset PYTHONPATH

Every every I fix it one way, it comes back again. Several answers help to fix it temporarily, but not for good. I have reinstalled python and python3 several times. What can I do from here?

vvvvv's user avatar

vvvvv

21k17 gold badges46 silver badges66 bronze badges

asked Jun 30, 2016 at 20:33

codyc4321's user avatar

7

For Python-3 try removing virtual environment files. And resetting it up.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3
edit fo

Community's user avatar

answered Aug 23, 2016 at 9:11

Anoop Malav's user avatar

Anoop MalavAnoop Malav

1,3711 gold badge9 silver badges6 bronze badges

11

For Windows10 User.

I was using python3.4 on Windows10. I installed python3.5. I couldn’t find PYTHONPATH, PYTHONHOME env variable. If I command python in CMD console, It kept using python3.4. I deleted python3.4. Whenever I command python in CMD console, it starts showing an error like below.

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

I searched to figure out my problem. Solution was simple. When you install python3.5, you can custom install and check Add Python to environment variables in Advanced Options.

I just leave here for case that someone have similar issues visit here so that they don’t waste their precious time much to figure out.

Community's user avatar

answered Aug 2, 2017 at 9:14

Jayground's user avatar

JaygroundJayground

1,7671 gold badge16 silver badges32 bronze badges

1

I was facing the same problem under Windows7. The error message looks like that:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

I have installed python 2.7(uninstalled now), and I checked «Add Python to environment variables in Advanced Options» while installing python 3.6. It comes out that the Environment Variable «PYTHONHOME» and «PYTHONPATH» is still python2.7.

Finally I solved it by modify «PYTHONHOME» to python3.6 install path and remove variable «PYTHONPATH«.

Eric Aya's user avatar

Eric Aya

69.1k35 gold badges179 silver badges250 bronze badges

answered Apr 23, 2018 at 9:40

Li Qiao's user avatar

Li QiaoLi Qiao

1311 silver badge3 bronze badges

For the same issue on Windows7

You will see an error like this if your environment variables/ system variables are incorrectly set:

Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'

Current thread 0x00001db4 (most recent call first):

Fixing this is really simple:

  1. When you download Python3.x version, and run the .exe file, it gives you an option to customize where in your system you want to install Python. For example, I chose this location: C:Program FilesPython36

  2. Then open system properties and go to «Advanced» tab (Or you can simply do this: Go to Start > Search for «environment variables» > Click on «Edit the system environment variables».) Under the «Advanced» tab, look for «Environment Variables» and click it. Another window with name «Environment Variables» will pop up.

  3. Now make sure your user variables have the correct Python path listed in «Path Variable». In my example here, you should see C:Program FilesPython36. If you do not find it there, add it, by selecting Path Variable field and clicking Edit.

  4. Last step is to double-check PYTHONHOME and PYTHONPATH fields under System Variables in the same window. You should see the same path as described above. If not add it there too.

Then click OK and go back to CMD terminal, and try checking for python. The issue should now be resolved. It worked for me.

answered Aug 14, 2017 at 4:31

dotpy_novice's user avatar

dotpy_novicedotpy_novice

3351 gold badge4 silver badges15 bronze badges

2

I had this error during migration to Ubuntu 17.10, and this solved the problem :

sudo dpkg-reconfigure python3

Maybe you will have to close your session and reconnect.

answered Nov 7, 2017 at 11:48

numahell's user avatar

numahellnumahell

1311 silver badge2 bronze badges

3

Look at /lib/python3.5 and you will see broken links to python libraries. Recreate it to working directory.

Next error —

./script/bin/pip3
Failed to import the site module
Traceback (most recent call last):
  File "/home/script/script/lib/python3.5/site.py", line 703, in <module>
    main()
  File "/home/script/script/lib/python3.5/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/home/script/script/lib/python3.5/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
  File "/home/script/script/lib/python3.5/types.py", line 166, in <module>
    import functools as _functools
  File "/home/script/script/lib/python3.5/functools.py", line 23, in <module>
    from weakref import WeakKeyDictionary
  File "/home/script/script/lib/python3.5/weakref.py", line 12, in <module>
    from _weakref import (
ImportError: cannot import name '_remove_dead_weakref'

fixed like this — https://askubuntu.com/questions/907035/importerror-cannot-import-name-remove-dead-weakref

cd my-virtualenv-directory
virtualenv . --system-site-packages

answered Aug 28, 2018 at 14:33

IvanTheFirst's user avatar

I had deleted rm -r /usr/lib/python*

dpkg -S '/usr/lib/python3*' | grep encodings

And then found I needed libpython3.10-minimal

sudo apt-get install --reinstall libpython3.10-minimal

I finally ran

sudo apt-get install --reinstall $(dpkg -S '/usr/lib/python3*' | cut -d ':' -f1 | cut -d ',' -f1 | sort | uniq | tr 'n' ' ')
sudo apt-get install --reinstall $(dpkg -S '/usr/lib/python2*' | cut -d ':' -f1 | cut -d ',' -f1 | sort | uniq | tr 'n' ' ')

To re-install all the packages I deleted files for

answered Sep 21, 2022 at 13:19

William Desportes's user avatar

Had the same problem when updating my mac to macOS Catalina, while using pipenv. Pipenv creates and manages a virtualenv for you, so the earlier suggestion from @Anoop-Malav is the same, just using pipenv to remove the virtual environment based on the current dir and reset it:

pipenv --rm
pipenv shell  # recreate a virtual env with your current Pipfile

answered Nov 18, 2019 at 11:51

qix's user avatar

qixqix

6,8081 gold badge53 silver badges64 bronze badges

2

I was facing this issue «ModuleNotFoundError: No module named ‘encodings» after updating to macOS Catalina.

I was having multiple versions of Python installed in my system.

Removing all the python versions(2.7 and 3.7.4) from macOS system and reinstalling the latest python 3.8 worked for me.

To remove a python from macOS, I’ve followed the instructions from here How to uninstall Python 2.7 on a Mac OS X 10.6.4?

The above link is for python 2.7 and but you can use the same for 3.7 also.

answered Dec 3, 2019 at 5:27

Kondal Kolipaka's user avatar

1

In my case just changing the permissions of anaconda folder worked:

sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda   

answered Aug 9, 2020 at 10:46

Apogentus's user avatar

ApogentusApogentus

6,2815 gold badges32 silver badges32 bronze badges

0

I got this error when try to launch MySql Workbench 8.0 on my macOS Catalina 10.15.3.

I solved this issue by installing Python 3.7 on my system.

I guess in future, when Workbench will have version greater than 8, it will require newer version of Python. Just look at the library path in the error and you will find required version.

answered Jan 23, 2021 at 21:50

Eldar Kurbanov's user avatar

I tried everything, deleted PYTHONPATH and PYTHONHOME — the error didn’t go away. I had overlooked that I had specified a python-home path under WSGIDaemonProcess in the wsgi configuration of a VirtualHost. I removed that and the error was gone.

answered Mar 30, 2022 at 16:27

Stephan's user avatar

I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH but it still didn’t go.
I checked with python -version and go to know that it was still taking the anaconda path.
I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH.
Issue Solved!

answered Nov 16, 2019 at 9:22

Satyam Gaba's user avatar

Because this is the first result in google I just want to add the following information for anybody else having problems with jails:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f079b16d740 (most recent call first):
Aborted (core dumped)

When attempting to import python into your jail you both need to link the dependencies and /usr/lib/pythonX.Y to [JAIL]/usr/lib/. Hope this helps.

answered Feb 5, 2020 at 23:24

Matt's user avatar

MattMatt

4593 silver badges12 bronze badges

3

I was facing same issue on a Debian server and for me the problem was that I’ve put my project inside the /root/ folder for which mod_wsgi didn’t have the rights to access. So I simply moved my project into /var/www/html/ and update my VirtualHost configuration.

answered Sep 7, 2021 at 13:14

Benbb96's user avatar

Benbb96Benbb96

1,7861 gold badge12 silver badges20 bronze badges

In my case, what worked was the following: I changed the env path in the conf from /home/vinzee/.pyenv/versions/envname/bin/ to /home/vinzee/.pyenv/versions/envname/ and it worked.

It seems the environment path needs to be the path to the root folder of the virtual environment (and not the path to ROOT_VENV/bin/).

You can additionally try without the trailing slash as others have suggested, but in my case, it worked both with and without it.

answered Oct 7, 2021 at 17:26

vvvvv's user avatar

vvvvvvvvvv

21k17 gold badges46 silver badges66 bronze badges

It seems this error can happen for a large variety of reasons (given the number of different answers on here).

For me, the issue was related to the fact that my app was deployed in a virtualenv, and the pyvenv.cfg file had the wrong permissions. It must be writable by the user uwsgi is running as (which in my case was http).

answered Nov 18, 2021 at 15:12

Ben Davis's user avatar

Ben DavisBen Davis

12.6k10 gold badges48 silver badges57 bronze badges

Just go to File -> Settings -> select Project Interpreter under Project tab -> click on the small gear icon -> Add -> System Interpreter -> select the python version you want in the drop down menu

this seemed to work for me

answered Nov 4, 2019 at 17:30

Balu B's user avatar

Balu BBalu B

131 silver badge2 bronze badges

1

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save.
I do not know how recommended it is to do that !

answered Feb 6, 2018 at 22:09

Pber6154's user avatar

0

Unfortunately I still have a problem for pip:

C:UsersArekDesktopWPy64-3860scripts>pip
Traceback (most recent call last):
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64librunpy.py", line
194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64librunpy.py", line
87, in _run_code
    exec(code, run_globals)
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64Scriptspip.exe__m
in__.py", line 4, in <module>
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalclimain.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalcliautocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalclimain_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalclicmdoptions.py", line 23, in <module>
    from pip._internal.cli.progress_bars import BAR_TYPES
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalcliprogress_bars.py", line 12, in <module>
    from pip._internal.utils.logging import get_indentation
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsite-packagesp
p_internalutilslogging.py", line 9, in <module>
    import logging.handlers
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64liblogginghandler
.py", line 26, in <module>
    import logging, socket, os, pickle, struct, time, re
  File "C:UsersArekDesktopWPy64-3860python-3.8.6.amd64libsocket.py", lin
 49, in <module>
    import _socket
ModuleNotFoundError: No module named '_socket'

Any tips here? Looks like _socket is missing.

Hello Guys, How are you all? Hope You all Are Fine. Today I am just trying to run python command And I am facing following error ImportError: No module named ‘encodings’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

Contents

  1. How ImportError: No module named ‘encodings’ Error Occurs ?
  2. How To Solve ImportError: No module named ‘encodings’ Error ?
  3. Solution 1: remove virtual environment files
  4. Solution 2: Update python PATH in Environment Variable
  5. Summary

How ImportError: No module named ‘encodings’ Error Occurs ?

I am just trying to run python command And I am facing following error.

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

How To Solve ImportError: No module named ‘encodings’ Error ?

  1. How To Solve ImportError: No module named ‘encodings’ Error ?

    To Solve ImportError: No module named ‘encodings’ Error You Just need to remove virtual environment files. Follow this command Just run this command rm -rf venv and then virtualenv -p /usr/bin/python3 venv/ Then source venv/bin/activate and then pip install -r requirements.txt. Second solution is In My case I just updated my python to Python 3.7 and still my Environment variable Path is Old and Suggesting Python 3.5 Solution is simple. When you install python3.7, you can custom install and check Add Python to environment variables in Advanced Options.

  2. ImportError: No module named ‘encodings’

    To Solve ImportError: No module named ‘encodings’ Error You Just need to remove virtual environment files. Follow this command Just run this command rm -rf venv and then virtualenv -p /usr/bin/python3 venv/ Then source venv/bin/activate and then pip install -r requirements.txt. Second solution is In My case I just updated my python to Python 3.7 and still my Environment variable Path is Old and Suggesting Python 3.5 Solution is simple. When you install python3.7, you can custom install and check Add Python to environment variables in Advanced Options.

Solution 1: remove virtual environment files

You Just need to remove virtual environment files. Follow this command.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

Now your error must be solved.

Solution 2: Update python PATH in Environment Variable

In My case I just updated my python to Python 3.7 and still my Environment variable Path is Old and Suggesting Python 3.5

Solution is simple. When you install python3.7, you can custom install and check Add Python to environment variables in Advanced Options.

Summary

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also, Read

  • ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

I have written a python code which uses the ‘Raster Surface Volume’ algorithm of QGIS Desktop 3.8.3. When I execute the python code, I am getting an error :

The system cannot find the path specified.
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00002218 (most recent call first):
Press any key to continue . . . 

I have imported the libraries as given below.

from osgeo import ogr, gdal
from gdalconst import *
from qgis.core import *
import qgis.utils, sys
from qgis.gui import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QFileInfo
app = QApplication([])
QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
QgsApplication.initQgis()
sys.path.append('C:/OSGeo4W64/apps/qgis/python/plugins')
import processing
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *
import os, glob 

In the ‘Environment Variables’, in the ‘path’ of ‘user variables’ section, I can find :

C:UserssreerajAppDataLocalProgramsPythonPython37Scripts
C:UserssreerajAppDataLocalProgramsPythonPython37 

I can also find the same in the ‘path’ of ‘system variables’ section in the ‘Environment Variables’.

In the folder ‘C:OSGeo4W64apps’, I can find 2 folders namely ‘Python37’ and ‘Python27’.

I have installed ‘python-3.7.4-amd64.exe’ in my computer before installing the ‘osgeo4w64’. Which means that I am using Python 3.7.4 in my computer and when I installed ‘OSGeo4W64’, I can find find a folder ‘Python37’ (along with ‘Python27’) which is integrated to QGIS Desktop 3.8.3.

Can anyone help me with the exact solution to this error ‘No module named encodings’ ?

As @user2856 suggested, I opened OSGeo4W command prompt, then executed py3_env, qt5_env and ran the script using python3 pathtoyourscript.py . Now, I got a QGIS import error :

from qgis.core import * ModuleNotFoundError: 
No module named 'qgis' . 

python-qgis.bat file in C:OSGeo4W64bin is given below :

@echo off
call "%~dp0o4w_env.bat"
call qt5_env.bat
call py3_env.bat
@echo off
path %OSGEO4W_ROOT%appsqgisbin;%PATH%
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT:=/%/apps/qgis
set GDAL_FILENAME_IS_UTF8=YES
rem Set VSI cache to be used as buffer, see #6448
set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%appsqgisqtplugins;%OSGEO4W_ROOT%appsqt5plugins
set PYTHONPATH=%OSGEO4W_ROOT%appsqgispython;%PYTHONPATH%

«%PYTHONHOME%python» %*

I have tried the accepted answer of @Germán Carrillo of Problem with import qgis.core when writing a stand-alone PyQGIS script by running var_entorno_osgeo4w.bat in OSGeo4W64 shell as given below :

run o-help for a list of available commands
C:OSGeo4W64>var_entorno_osgeo4w.bat
C:OSGeo4W64>set PYTHONPATH=C:OSGeo4W64appsqgispython
C:OSGeo4W64>set PATH=C:OSGeo4W64appsqgisbin;C:OSGEO4~1appsPython37Scripts;C:OSGEO4~1bin;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSsystem32WBem
C:OSGeo4W64>

Still, I am unable to solve this issue. How can I solve this QGIS import error : No module named ‘qgis’ ?

7 ответов

Для пользователя Windows10.

Я использовал python3.4 в Windows10. Я установил python3.5. Я не мог найти переменную PYTHONPATH, PYTHONHOME env. Если я пишу python в консоли CMD, он продолжал использовать python3.4. Я удалил python3.4. Всякий раз, когда я командую python в консоли CMD, он начинает показывать ошибку, как показано ниже.

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

Я искал свою проблему. Решение было простым. Когда вы устанавливаете python3.5, вы можете настроить и установить Добавить Python в переменные среды в Дополнительные параметры.

Я просто останусь здесь для случая, что у кого-то есть подобные проблемы, посещайте здесь, чтобы они не тратили драгоценное время на многое, чтобы понять.

Jayground
02 авг. 2017, в 10:22

Поделиться

У меня была эта ошибка во время миграции на Ubuntu 17.10, и это решило проблему:

sudo dpkg-reconfigure python3

Возможно, вам придется закрыть сеанс и снова подключиться.

numahell
07 нояб. 2017, в 13:00

Поделиться

Для той же самой проблемы в Windows7

Вы увидите ошибку, подобную этой, если неверно установлены переменные среды/системные переменные:

Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'

Current thread 0x00001db4 (most recent call first):

Фиксирование это очень просто:

  • Когда вы загружаете версию Python3.x и запускаете файл .exe, он дает вам возможность настроить, где в вашей системе вы хотите установить Python. Например, я выбрал это местоположение: C:Program FilesPython36

  • Затем откройте свойства системы и перейдите на вкладку « Дополнительно» (или вы можете просто сделать это: Перейти в «Пуск» > «Поиск» переменных среды » > Нажмите» Изменить переменные системной среды «.) На вкладке» Дополнительно «найдите» Переменные среды «и щелкните по нему. Появится другое окно с именем» Переменные среды».

  • Теперь убедитесь, что ваши пользовательские переменные имеют правильный путь Python, указанный в «Переменная пути». В моем примере здесь вы должны увидеть C:Program FilesPython36. Если вы его не найдете, добавьте его, выбрав поле «Переменная переменная» и нажав «Изменить».

  • Последний шаг — дважды проверить поля PYTHONHOME и PYTHONPATH в разделе Системные переменные в том же окне. Вы должны увидеть тот же путь, как описано выше. Если не добавить его там тоже.

Затем нажмите «ОК» и вернитесь на CMD-терминал и попробуйте проверить на python. Теперь проблема должна быть решена. Это сработало для меня.

dotpy_novice
14 авг. 2017, в 05:22

Поделиться

Я столкнулся с той же проблемой под Windows7. Сообщение об ошибке выглядит так:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

Я установил Python 2.7 (теперь удален), и я установил флажок «Добавить Python к переменным среды в Дополнительные параметры» при установке Python 3.6. Получается, что переменная окружения » PYTHONHOME » и » PYTHONPATH » все еще python2.7.

Наконец, я решил это, изменив » PYTHONHOME » на путь установки python3.6 и удалив переменную » PYTHONPATH «.

Li Qiao
23 апр. 2018, в 11:38

Поделиться

Посмотрите /lib/python3.5 и вы увидите неработающие ссылки на библиотеки Python. Пересоздайте его в рабочий каталог.

Следующая ошибка —

./script/bin/pip3
Failed to import the site module
Traceback (most recent call last):
  File "/home/script/script/lib/python3.5/site.py", line 703, in <module>
    main()
  File "/home/script/script/lib/python3.5/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/home/script/script/lib/python3.5/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
  File "/home/script/script/lib/python3.5/types.py", line 166, in <module>
    import functools as _functools
  File "/home/script/script/lib/python3.5/functools.py", line 23, in <module>
    from weakref import WeakKeyDictionary
  File "/home/script/script/lib/python3.5/weakref.py", line 12, in <module>
    from _weakref import (
ImportError: cannot import name '_remove_dead_weakref'

исправлено вот так — https://askubuntu.com/questions/907035/importerror-cannot-import-name-remove-dead-weakref

cd my-virtualenv-directory
virtualenv . --system-site-packages

IvanTheFirst
28 авг. 2018, в 15:04

Поделиться

Я также мог бы это исправить. PYTHONPATH и PYTHONHOME были причиной.

запустить это в терминале

   touch ~/.bash_profile
   open ~/.bash_profile

а затем удалите все ненужные части этого файла и сохраните. Я не знаю, как рекомендуется это делать!

Pber6154
06 фев. 2018, в 22:11

Поделиться

Ещё вопросы

  • 0Метод PHP GetPayload не возвращает тело сообщения
  • 1Трудоемкие задачи на веб-сайтах
  • 1Почему каждый второй коэффициент nfty’s fft является обратным к тому, что должно быть? [Дубликат]
  • 0Получить номер отдельной строки внутри строки
  • 0Запретить добавление идентификатора для элементов формы в библиотеке тегов Spring
  • 0Загрузка файла на сервер с помощью AngularJS и Java Servlet
  • 1Удалить строку под определенным значением панды
  • 1Получение собственных сообщений от Chrome на Java
  • 0CakePhp настроить функцию перевода
  • 1Android неизвестное исключение
  • 1Entity Framework СОЕДИНЯЕТСЯ, когда тип данных не совпадает
  • 1Итерация по параллельным спискам и преобразование текста с разделителями табуляции в одном списке в путь CSV в другом
  • 0Как автоматически загрузить изображение на сервер, используя Javascript
  • 1Как сделать сериализацию с рекурсивным обходом?
  • 1Selenium получить активную вкладку
  • 1Ошибка автоматического перехода на следующую страницу в приложении Магазина Windows
  • 1DependencyProperty объекта UserControl равен нулю, если элемент UserControl имеет DataContext.
  • 0Замените ресурсы на путь CDN, используя grunt
  • 1Как освободить память, используемую фреймом данных Pandas, но не срезами?
  • 1Многопоточный код для работы с использованием настроенного количества потоков
  • 0Установите переменные по умолчанию в функциях MySQL, если значения не верны
  • 1JavaScript / AppleScript: получите текущее время HTML-видео
  • 0Android: fromhtml оставляет детали шрифта в строке
  • 0Не могу подтвердить код отслеживания Google на странице GitHub
  • 1Как утверждать, что путь выполнения не выполняется более одного раза в Java?
  • 1Защита идентификатора сеанса Cookie в Weblogic портит создание сеанса
  • 1Списки в списках
  • 0JQuery: изменить значение CSS, если опция выбрана
  • 1Одновременно суммируйте два ключа в списке диктов по нескольким предметам
  • 0Что я делаю неправильно, загружая этот массив JS?
  • 1JS: Фильтр массив только для непустых и тип строковых значений
  • 1Android: представление списка с миниатюрой
  • 1Как фильтровать уникальные строки двумерного массива на основе вложенных элементов и суммируемых значений одновременно в Javascript
  • 0Как я могу изменить этот код, чтобы он работал с IE 11?
  • 0Расширение Magento Checkout — перейти к следующему шагу в Checkout
  • 0Как сделать так, чтобы поле редактирования отображалось в позиции элемента, нажатой с угловым
  • 1как сказать egit игнорировать некоторые типы файлов
  • 0Использование погодного API
  • 1Случайное расписание Alarm Manager с календарем
  • 0C ++ программа расчета стоимости ковровых покрытий
  • 0Как предварительно выбрать (предварительно щелкнуть) первую или вторую строку таблицы в angularjs?
  • 1Переключить / Case в Matlab на If / Else Python
  • 1Продолжайте получать ошибки во время выполнения из библиотеки MathNet Numerics. Не могу заставить его работать
  • 0D3 Каждый метод работает не так, как ожидалось
  • 0Как определить, имеет ли HTML-элемент поведение AngularJS?
  • 0Измените формат файла на baracuda на сервере mariadb
  • 1Кнопка меню не работает на эмуляторе в приложении Карт
  • 1Как создать заголовок запроса авторизации?
  • 1pointcut для унаследованных методов
  • 0Как перезагрузить применение директивы при изменении структуры div ng-repeat?

python – ImportError: No module named encodings

For Python-3 try removing virtual environment files. And resetting it up.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3
edit fo

For Windows10 User.

I was using python3.4 on Windows10. I installed python3.5. I couldnt find PYTHONPATH, PYTHONHOME env variable. If I command python in CMD console, It kept using python3.4. I deleted python3.4. Whenever I command python in CMD console, it starts showing an error like below.

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named encodings

I searched to figure out my problem. Solution was simple. When you install python3.5, you can custom install and check Add Python to environment variables in Advanced Options.

I just leave here for case that someone have similar issues visit here so that they dont waste their precious time much to figure out.

python – ImportError: No module named encodings

I was facing the same problem under Windows7. The error message looks like that:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named encodings

Current thread 0x000011f4 (most recent call first):

I have installed python 2.7(uninstalled now), and I checked Add Python to environment variables in Advanced Options while installing python 3.6. It comes out that the Environment Variable PYTHONHOME and PYTHONPATH is still python2.7.

Finally I solved it by modify PYTHONHOME to python3.6 install path and remove variable PYTHONPATH.

Related posts on python :

  • Plot Ellipse with matplotlib.pyplot (Python)
  • List of zeros in python
  • python – How do I put a variable’s value inside a string?
  • python argparse choices with a default choice
  • python – Anaconda failed to create process
  • Conversion from JavaScript to Python code?
  • python – collapse cell in jupyter notebook
  • python – How to use norm.ppf()?

Issue27054

Created on 2016-05-18 21:59 by lauer@wpi.edu, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (16)
msg265838 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-18 21:59
Hello,

I am a university professor who regularly teaches classes in Python programming, particular to students who are NOT computer science majors.

In preparing my course materials for next fall, I have been struggling with setting up a Python 3.5.1 environment on my Windows computer (similar to what most of my students will use).

I continually get the error "Fatal Python error: Py_Initialize: unable to load the file system codec
                                                ImportError: No module named 'encodings'"

This seems to happen with Python 3.5.1 as well as Python 3.5.0.

Nothing related to Python works:- not Python itself, not pip.

My platform is Windows 7 Enterprise, Service Pack 1.

*         I used the installation file "python-3.5.1-amd64.exe" downloaded from the official Python download site.

*         During installation, I selected "Add Python 3.5 to PATH" and "Customize installation".

*         Under "Advanced Options," I selected "Install for all users"

I have tried various other installation options, and nothing is better.

I also tried it on a Windows 10 platform. In that case, Python and IDLE are installed correctly, but I any attempt to use pip to add or install other packages fails with a different error.

For pedagogical reasons, I prefer the simply Python-IDLE environment to the packages such as Miniconda3, but installing Miniconda3 did not help either.

Am I missing something obvious?

Regards,

Hugh C. Lauer
Department of Computer Science
Worcester Polytechnic Institute
Worcester, Massachusetts, USA
msg265855 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-19 13:15
Upon further investigation, I find lots of encodings in the folder C:Program FilesPython35Libencodings and lots of compiled encodings in the subfolder __pycache__ .

Somehow, these are not being found by Python itself, or there is something missing from the installation.

I investigated the registry. A search for "encodings" turns up lots of registry entries but none associated with Python.

Regards,

Hugh C. Lauer
Worcester Polytechnic Institute
msg265861 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-19 14:38
On a hunch, I uninstalled Python 3.5.1 and reinstalled it for the current user only, to see if it would make a difference in the association of the encodings in the Registry.

There was no difference. The original error message still appears.

Regards,

Hugh C. Lauer
Worcester Polytechnic Institute
msg265862 — (view) Author: Stefan Krah (skrah) * (Python committer) Date: 2016-05-19 14:49
I can only comment on the Windows 10 issue: I think I did the install
with "Right-click -> Run as administrator" and then installed for
all users.  Encodings, pip and everything else works here.
msg265865 — (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2016-05-19 14:55
Hugh, could you check your environment and see if you have any PYTHON* variables set, particularly PYTHONHOME?
msg265866 — (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2016-05-19 14:55
To list environment variable, you can open cmd.exe and type the command "set".
msg265867 — (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2016-05-19 14:57
Also, I suspect your pip issue on Windows 10 is due to the fact that you need to either specify the --user flag or run pip as administrator, since your user account can't write to the global site-packages under Program Files.
msg265870 — (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2016-05-19 15:56
Here's some pretty compelling evidence for a bad PYTHONHOME setting:

C:>set PYTHONHOME=C:pathnothere

C:>py -3.5
Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'

Current thread 0x00001db4 (most recent call first):

C:>set PYTHONHOME=C:Python27

C:>py -3.5
Fatal Python error: Py_Initialize: unable to load the file system codec
  File "C:Python27\libencodings__init__.py", line 123
    raise CodecRegistryError,
                            ^
SyntaxError: invalid syntax

Current thread 0x00000664 (most recent call first):

C:>set PYTHONHOME=

C:>py -3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
msg265907 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-20 02:03
Thanks, I will try it when I get out of airports.

Hugh Lauer

On May 19, 2016 11:56 AM, Zachary Ware <report@bugs.python.org> wrote:

>

>
> Zachary Ware added the comment:
>
> Here's some pretty compelling evidence for a bad PYTHONHOME setting:
>
> C:>set PYTHONHOME=C:pathnothere
>
> C:>py -3.5
> Fatal Python error: Py_Initialize: unable to load the file system codec
> ImportError: No module named 'encodings'
>
> Current thread 0x00001db4 (most recent call first):
>
> C:>set PYTHONHOME=C:Python27
>
> C:>py -3.5
> Fatal Python error: Py_Initialize: unable to load the file system codec
>   File "C:Python27\libencodings__init__.py", line 123
>     raise CodecRegistryError,
>                             ^
> SyntaxError: invalid syntax
>
> Current thread 0x00000664 (most recent call first):
>
> C:>set PYTHONHOME=
>
> C:>py -3.5
> Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
>
> ----------
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <http://bugs.python.org/issue27054>
> _______________________________________
msg266334 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-25 12:00
I am back from my travels.

Thanks very much, Stefan. Running as administrator did the trick for Windows 10 installations. I now have a reliable, repeatable protocol that I can give to students with little computing experience that will enable them to install Python on their Windows 10 laptops.

Hugh Lauer
Worcester Polytechnic Institute
msg266336 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-25 12:04
I am back from my travels.

Thanks Zachary for this. On Windows 10, no PYTHON or PYTHONHOME environment variable is set. On Windows 7, they are set. Moreover, even though I am installing Python 3.5.1, the refer to C:Program filesPython34 !

I will continue to experiment with this.

Regards,

Hugh Lauer
Worcester Polytechnic Institute
msg266341 — (view) Author: Hugh C. Lauer (lauer@wpi.edu) Date: 2016-05-25 13:01
All, it seems that installation of Python 3.5.1 on Windows 7 must also be done as administrator. Once I did that, the installation of Python 3.5.1, numpy 1.11.0, and matplotlib 1.5.1 all went seamlessly.

The only environment variable that was changed was to add the Python installation directory to the PATH environment variable.

Regards,

Hugh C. Lauer
Worcester Polytechnic Institute
msg266384 — (view) Author: Steve Dower (steve.dower) * (Python committer) Date: 2016-05-25 18:13
I suspect PYTHONHOME is the problem and not the installation method. There have been thousands of (presumably successful) installations of Python 3.5, and I expect most of them are just for the current user (as that's the default). If these were all failing for this reason, we'd have heard before now :)

There are likely to be some configurations that will cause the initial install to fail if you aren't running as an administrator, but that doesn't sound like the issue here.

Rogue installers that write to Python's registry keys (e.g. Anaconda) are more likely to cause problems here, as are those that globally set environment variables like PYTHONHOME/PYTHONPATH. If, like me, you install a lot of different bundles to figure out which is best, then some of these may be lingering around.

But I'm 99.99% certain that our installer is not at fault and there's nothing to fix here.
msg309489 — (view) Author: Sabuj Pattanayek (Sabuj Pattanayek) Date: 2018-01-05 00:08
I can confirm that this does happen if you don't install as admin. I confirmed that I didn't have PYTHONHOME or PYTHONPATH set and I still got a similar error (except it was for the site module) for the python 3.4.4 installer. setting pythonhome and pythonpath to blank does make it work, but so does just installing the exe/msi as admin.

Note this error does not happen with the python 2.7 installers even if you don't install as admin.
msg366042 — (view) Author: E (ergun) Date: 2020-04-09 11:42
python3 gave the error but I could sudo python3. To solve:
export PYTHONHOME=
export PYTHONPATH=
msg366075 — (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2020-04-09 15:57
> I continually get the error
> "Fatal Python error: Py_Initialize: unable to load the file system codec
> ImportError: No module named 'encodings'"

FYI I enhanced this error in Python 3.8 to "dump the Python path configuration". Example:

$ PYTHONHOME=x PYTHONPATH=y python3.8
Python path configuration:
  PYTHONHOME = 'x'
  PYTHONPATH = 'y'
  program name = 'python3.8'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = '/usr/bin/python3.8'
  sys.base_prefix = 'x'
  sys.base_exec_prefix = 'x'
  sys.executable = '/usr/bin/python3.8'
  sys.prefix = 'x'
  sys.exec_prefix = 'x'
  sys.path = [
    'y',
    'x/lib64/python38.zip',
    'x/lib64/python3.8',
    'x/lib64/python3.8/lib-dynload',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f50aaad8740 (most recent call first):
<no Python frame>

It should be easier for users to understand their mistake.

In general, leave PYTHONHOME empty/unset unless you understand very well what you are doing ;-)
History
Date User Action Args
2022-04-11 14:58:31 admin set github: 71241
2020-04-09 15:57:25 vstinner set messages:
+ msg366075
2020-04-09 11:42:38 ergun set nosy:
+ ergun
messages:
+ msg366042
2018-01-05 00:08:58 Sabuj Pattanayek set nosy:
+ Sabuj Pattanayek
messages:
+ msg309489
2016-05-25 18:37:41 zach.ware set stage: resolved
2016-05-25 18:13:04 steve.dower set status: open -> closed
resolution: not a bug
messages:
+ msg266384
2016-05-25 13:01:51 lauer@wpi.edu set messages:
+ msg266341
2016-05-25 12:04:52 lauer@wpi.edu set messages:
+ msg266336
2016-05-25 12:00:47 lauer@wpi.edu set messages:
+ msg266334
2016-05-20 02:03:05 lauer@wpi.edu set messages:
+ msg265907
2016-05-19 18:56:33 ppperry set type: crash
2016-05-19 15:56:04 zach.ware set messages:
+ msg265870
2016-05-19 14:57:41 zach.ware set messages:
+ msg265867
2016-05-19 14:55:50 vstinner set nosy:
+ vstinner
messages:
+ msg265866
2016-05-19 14:55:14 zach.ware set messages:
+ msg265865
2016-05-19 14:49:58 skrah set nosy:
+ skrah
messages:
+ msg265862
2016-05-19 14:38:11 lauer@wpi.edu set messages:
+ msg265861
2016-05-19 13:15:00 lauer@wpi.edu set messages:
+ msg265855
2016-05-18 23:50:29 ned.deily set nosy:
+ paul.moore, tim.golden, zach.ware, steve.dower

components:
+ Installation, Windows
versions:
+ Python 3.5

2016-05-18 21:59:26 lauer@wpi.edu create

Понравилась статья? Поделить с друзьями:
  • No mans sky не запускается windows 7
  • No man sky windows 10 discovery servers
  • No locked doors no windows barred
  • No listening sockets available shutting down windows
  • No listening sockets available apache windows