No module named site windows

Python (Windows) – ImportError: No module named site

Posted by: admin November 17, 2017 Leave a comment

I am trying to install Python for the first time. I downloaded the following installer from the Python website:
Python 2.7.1 Windows Installer (Windows binary — does not include source). I then ran the installer, selected ‘All Users’ and all was fine. I installed Python into the default location:

Next, to test that Python was installed correctly, I navigated to my Python Directory, and ran the “python” command in the windows cmd prompt. It returns me the following error:

ImportError: No module named site

When I do ‘python -v’ I get the following:

#installing zipimport hook
import zipimport # builtin
#installed zipimport hook
#ImportError: No module named site
#clear builtin._
#clear sys.path
#clear sys.argv
#clear sys.ps1
#clear sys.ps2
#clear sys.exitfunc
#clear sys.exc_type
#clear sys.exc_value
#clear sys.exc_traceback
#clear sys.last_type
#clear sys.last_value
#clear sys.last_traceback
#clear sys.path_hooks
#clear sys.path_importer_cache
#clear sys.meta_path
#clear sys.flags
#clear sys.float_info
#restore sys.stdin
#restore sys.stdout
#restore sys.stderr
#cleanup main
#cleanup [1 ] zipimport
#cleanup [1 ] signal
#cleanup [1 ] exceptions
#cleanup [1 ] _warnings
#cleanup sys
#cleanup builtin
#cleanup ints: 6 unfreed ints
#cleanup floats

When I do dir C:\Python27\Lib\site.py* I get the following:

C:\Users\Mimminito>dir C:\Python27\Lib\site.py*
Volume in drive C has no label.
Volume Serial Number is DAB9-A863

Directory of C:\Python27\Lib

13/11/2010 20:08 20,389 site.py
1 File(s) 20,389 bytes
0 Dir(s) 694,910,976 bytes free

Hey, I’ve been looking into this problem for myself for almost a day and finally had a breakthrough. Try this:

Setting the PYTHONPATH / PYTHONHOME variables

Right click the Computer icon in the start menu, go to properties.
On the left tab, go to Advanced system settings. In the window that comes up, go to the Advanced tab, then at the bottom click Environment Variables. Click in the list of user variables and start typing Python, and repeat for System variables, just to make certain that you don’t have mis-set variables for PYTHONPATH or PYTHONHOME. Next, add new variables (I did in System rather than User, although it may work for User too): PYTHONPATH, set to C:\Python27\Lib. PYTHONHOME, set to C:\Python27.

Hope this helps!

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

Make sure you don’t have a trailing ‘\’ on the PYTHON* vars, this seems to break it aswel.

I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by export ing PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7

Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.

to set this permanently for subsequent command prompts

Are you trying to run Windows Python from Cygwin? I’m having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I’ll need to install python through cygwin to get it working.

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

For me it happened because I had 2 versions of python installed – python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.

If somebody will find that it’s still not working under non-admin users:

you need to set ‘–always-unzip’ option for easy_install:

It will unzip your egg files and will allow import to find em.

Locate site.py and add its path in PYTHONPATH. This will solve your problem.

You may try the Open Source Active Python Setup which is a well done Python installer for Windows.
You just have to desinstall your version and install it…

Читайте также:  Usb клавиатура с usb портами windows

I up voted slckin’s answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5.
I renamed it to C:\Python27\ and it resolved the problem.

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same “ No module named site ” error. I’ve set PYTHONHOME to c:\Python27 and it’s working. But the mystery remains why this is now needed when it wasn’t with previous releases. And, if it is needed, why doesn’t the installer set this var?

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.

Джанго 1.8 Uwsgi — ImportError: No module named site. Пути проверил, указал. Что делать?

uwsgi установлен глобально.

работаю из виртуального окружения с именем venv

Создаю для запуска uwsgi

[uwsgi]
socket = /home/dbag/dbs/dbs.sock
virtualenv = /home/dbag/venv/
chdir = /home/dbag/dbs/mtest
master = True
workers = 8
module = mtest.wsgi:application
plugins = python34, python3
uid = www-data
gid = www-data
chmod-socket = 777
pythonpath = /home/dbag/venv/
pythonpath = /home/dbag/venv/lib/python3.4
pythonpath = /home/dbag/venv/lib/python3.4/site-packages

/dbs$ uwsgi —ini /home/dbag/dbs/1.conf

current working directory: /home/dbag/dbs
detected binary path: /usr/local/bin/uwsgi
chdir() to /home/dbag/dbs/mtest

your processes number limit is 1868
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with —thunder-lock)
uwsgi socket 0 bound to UNIX address /home/dbag/dbs/dbs.sock fd 3

Python version: 2.7.9 (default, Apr 2 2015, 15:37:21) [GCC 4.9.2]
Set PythonHome to /home/dbag/venv/

Вижу ошибку.
ImportError: No module named site

Проверяю пути к библиотекам:
(venv)dbag@work:

/dbs$ python -c «from distutils.sysconfig import get_python_lib; print (get_python_lib())»
/home/dbag/venv/lib/python3.4/site-packages
И это совпадает с тем, что у меня написано!

Проверяю версию джанго:
(venv)dbag@work:

/dbs$ python -c «import django; print (django.VERSION);»
(1, 8, 4, ‘final’, 0)

Ничего не понимаю. 🙁 Смущает еще версия питона: Python version: 2.7.9, при том, что если просто его запустить:
(venv)dbag@work:

/dbs$ python
Python 3.4.3 (default, Mar 26 2015, 22:03:40)

Пересоздавать окружение venv пробовал. Система ubuntu 15.04

Решение проблем с модулями и пакетами Python

Я с завидной регулярностью сталкиваюсь со всевозможными ошибками, так или иначе связанными с модулями Python. Существует огромное количество разнообразных модулей Python, которые разработчики активно используют, но далеко не всегда заботятся об установке зависимостей. Некоторые даже не удосуживаются их документировать. Параллельно существует две мажорные версии Python: 2 и 3. В разных дистрибутивах отдано предпочтение одной или другой версии, по этой причине самостоятельно установленную программу в зависимости от дистрибутива нужно при запуске предварять python или python2/python3. Например:

Причём обычно не происходит никаких проверок и угадали ли вы с выбором версии или нет вы узнаете только при появлении первых ошибок, вызванных неправильным синтаксисом программного кода для данной версии.

Также прибавляет путаницу то, что модули можно установить как из стандартного репозитория дистрибутивов, так и с помощью pip (инструмент для установки пакетов Python).

Цель этой заметки — рассмотреть некоторые характерные проблемы модулей Python. Все возможные ошибки вряд ли удастся охватить, но описанное здесь должно помочь понять, в каком примерно направлении двигаться.

Отсутствие модуля Python

Большинство ошибок модулей Python начинаются со строк:

В них трудно разобраться, поэтому поищите фразы вида:

  • ModuleNotFoundError: No module named
  • No module named
  • ImportError: No module named

За ними следует название модуля.

Поищите по указанному имени в системном репозитории, или попробуйте установить командой вида:

Пакет Python установлен, но программа его не видит

Причина может быть в том, что вы установили модуль для другой версии. Например, программа написана на Python3, а вы установили модуль с этим же названием, но написанный на Python2. В этом случае он не будет существовать для программы. Поэтому нужно правильно указывать номер версии.

Читайте также:  Windows self extracting installer

Команда pip также имеет свои две версии: pip2 и pip3. Если версия не указана, то это означает, что используется какая-то из двух указанных (2 или 3) версий, которая является основной в системе. Например, сейчас в Debian и производных по умолчанию основной версией Python является вторая. Поэтому в репозитории есть два пакета: python-pip (вторая версия) и python3-pip (третья).

В Arch Linux и производных по умолчанию основной версией является третья, поэтому в репозиториях присутствует пакет python-pip (третья версия) и python2-pip (вторая).

Это же самое относится к пакетам Python и самому Python: если версия не указана, значит имеется ввиду основная для вашего дистрибутива версия. По этой причине многие пакеты в репозитории присутствуют с двумя очень похожими названиями.

Установлена новая версия модуля, но программа видит старую версию

Я несколько раз сталкивался с подобными необъяснимыми ошибками.

Иногда помогает удаление модуля командой вида:

Также попробуйте удалить его используя системный менеджер пакетов.

Если модуль вам нужен, попробуйте вновь установить его и проверьте, решило ли это проблему.

Если проблема не решена, то удалите все файлы модуля, обычно они расположены в папках вида:

Ошибки с фразой «AttributeError: ‘NoneType’ object has no attribute»

Ошибки, в которых присутствует слово AttributeError, NoneType, object has no attribute обычно вызваны не отсутствием модуля, а тем, что модуль не получил ожидаемого аргумента, либо получил неправильное число аргументов. Было бы правильнее сказать, что ошибка вызвана недостаточной проверкой данных и отсутствием перехвата исключений (то есть программа плохо написана).

В этих случаях обычно ничего не требуется дополнительно устанавливать. В моей практике частыми случаями таких ошибок является обращение программы к определённому сайту, но сайт может быть недоступен, либо API ключ больше недействителен, либо программа не получила ожидаемые данные по другим причинам. Также программа может обращаться к другой программе, но из-за ошибки в ней получит не тот результат, который ожидала, и уже это вызывает приведённые выше ошибки, которые мы видим.

Опять же, хорошо написанная программа в этом случае должна вернуть что-то вроде «информация не загружена», «работа программы N завершилась ошибкой» и так далее. Как правило, нужно разбираться с причиной самой первой проблемы или обращаться к разработчику.

Модуль установлен, но при обновлении или обращении к нему появляется ошибки

Это самая экзотическая ошибка, которая вызвана, видимо, повреждением файлов пакета. К примеру, при попытке обновления я получал ошибку:

При этом сам модуль установлен как следует из самой первой строки.

Проблема может решиться удалением всех файлов пакета (с помощью rm) и затем повторной установки.

К примеру в рассматриваемом случае, удаление:

После этого проблема с модулем исчезла.

Заключение

Пожалуй, это далеко не полный «справочник ошибок Python», но если вы можете сориентироваться, какого рода ошибка у вас возникла:

  • отсутствует модуль
  • модуль неправильной версии
  • модуль повреждён
  • внешняя причина — программа не получила ожидаемые данные

Так вот, если вы хотя бы примерно поняли главную причину, то вам будет проще понять, в каком направлении двигаться для её решения.

Python (Windows) – ImportError: No module named site

Posted by: admin December 7, 2017 Leave a comment

I am trying to install Python for the first time. I downloaded the following installer from the Python website:
Python 2.7.1 Windows Installer (Windows binary — does not include source). I then ran the installer, selected ‘All Users’ and all was fine. I installed Python into the default location:

Next, to test that Python was installed correctly, I navigated to my Python Directory, and ran the “python” command in the windows cmd prompt. It returns me the following error:

ImportError: No module named site

When I do ‘python -v’ I get the following:

#installing zipimport hook
import zipimport # builtin
#installed zipimport hook
#ImportError: No module named site
#clear builtin._
#clear sys.path
#clear sys.argv
#clear sys.ps1
#clear sys.ps2
#clear sys.exitfunc
#clear sys.exc_type
#clear sys.exc_value
#clear sys.exc_traceback
#clear sys.last_type
#clear sys.last_value
#clear sys.last_traceback
#clear sys.path_hooks
#clear sys.path_importer_cache
#clear sys.meta_path
#clear sys.flags
#clear sys.float_info
#restore sys.stdin
#restore sys.stdout
#restore sys.stderr
#cleanup main
#cleanup [1 ] zipimport
#cleanup [1 ] signal
#cleanup [1 ] exceptions
#cleanup [1 ] _warnings
#cleanup sys
#cleanup builtin
#cleanup ints: 6 unfreed ints
#cleanup floats

When I do dir C:\Python27\Lib\site.py* I get the following:

C:\Users\Mimminito>dir C:\Python27\Lib\site.py*
Volume in drive C has no label.
Volume Serial Number is DAB9-A863

Directory of C:\Python27\Lib

13/11/2010 20:08 20,389 site.py
1 File(s) 20,389 bytes
0 Dir(s) 694,910,976 bytes free

Читайте также:  Служба поддержки mac os

Hey, I’ve been looking into this problem for myself for almost a day and finally had a breakthrough. Try this:

Setting the PYTHONPATH / PYTHONHOME variables

Right click the Computer icon in the start menu, go to properties.
On the left tab, go to Advanced system settings. In the window that comes up, go to the Advanced tab, then at the bottom click Environment Variables. Click in the list of user variables and start typing Python, and repeat for System variables, just to make certain that you don’t have mis-set variables for PYTHONPATH or PYTHONHOME. Next, add new variables (I did in System rather than User, although it may work for User too): PYTHONPATH, set to C:\Python27\Lib. PYTHONHOME, set to C:\Python27.

Hope this helps!

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

Make sure you don’t have a trailing ‘\’ on the PYTHON* vars, this seems to break it aswel.

I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by export ing PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7

Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.

to set this permanently for subsequent command prompts

Are you trying to run Windows Python from Cygwin? I’m having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I’ll need to install python through cygwin to get it working.

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

For me it happened because I had 2 versions of python installed – python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.

If somebody will find that it’s still not working under non-admin users:

you need to set ‘–always-unzip’ option for easy_install:

It will unzip your egg files and will allow import to find em.

Locate site.py and add its path in PYTHONPATH. This will solve your problem.

You may try the Open Source Active Python Setup which is a well done Python installer for Windows.
You just have to desinstall your version and install it…

I up voted slckin’s answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5.
I renamed it to C:\Python27\ and it resolved the problem.

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same “ No module named site ” error. I’ve set PYTHONHOME to c:\Python27 and it’s working. But the mystery remains why this is now needed when it wasn’t with previous releases. And, if it is needed, why doesn’t the installer set this var?

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.

Оцените статью