- Как изменить PYTHONPATH на Windows
- Краткая инструкция
- Подробное объяснение
- Пролог
- Небольшое пояснение по п.1
- Небольшое пояснение по п.2
- Небольшое пояснение по п.3
- Эпилог
- How do you correctly set the PYTHONPATH variable on Windows?
- 3 Answers 3
- How to add to the PYTHONPATH in Windows, so it finds my modules/packages?
- 22 Answers 22
- Just use the standard package site , which was made for this job!
Как изменить PYTHONPATH на Windows
Вы читаете эту статью, потому что пользуетесь:
… и хотите изменить PYTHONPATH.
Краткая инструкция
- Откройте C:\Users\ \Anaconda3\Lib\site-packages
- Создайте файл python37.pth
- Измените файл и добавьте в него строку C:\\Users\\ \\my_module
Подробное объяснение
Пролог
В большинстве случаев достаточно изменения PYTHONPATH из GUI настроек. Почему так — подробно объясняется на Stack Overflow .
Небольшое пояснение по п.1
Если у вас нет C:\Users\ \Anaconda3\Lib\site-packages, то замените C:\Users\ на путь к Anaconda 3.
Небольшое пояснение по п.2
Если вы работаете в Python 3.7, то создайте файл под названием python37.pth. Для остальных версий создавайте файл python .pth.
- Не знаете, в какой версии работаете?
Поищите похожий на python .dll файл вот здесь: C:\Users\ \Anaconda3\. Название версии указано в . Его нужно присвоить файлу.pth. - Windows действует на нервы и не дает создать файл с расширением.pth?
Такие файлы есть в папке C:\Users\ \Anaconda3\Lib\ site-packages. Скопируйте один из этих файлов и измените его расширение. - Прочитали где-то, что лучше создавать ._pth, а не .pth?
Файл ._pth полностью заменяет существующий путь. А .pth добавляет свое содержимое к уже существующему пути. Более подробно объясняется здесь .
Небольшое пояснение по п.3
Предположим, что SuperCoolClass, который вы хотите импортировать, находится в C:\Users\ \my_project_folder\ my_awesome_file.py.
Тогда откройте недавно созданный файл python .pth в своем любимом текстовом редакторе (пожалуйста, не говорите, что это Vim!) и добавьте туда вот эту строку:C:\\Users\\ \\my_project_folder.
Да-да, с этими раздражающими двойными слешами \\ .
И да, без кавычек “” .
Вот и все.
Теперь вы, как любой нормальный человек, сможете импортировать файлы, откуда угодно:
from my_awesome_file import SuperCoolClass .
Эпилог
Добавлять здесь особо нечего. Надеюсь, 2 часа нервотрепки и час на написание статьи сэкономят ваше время. Удачи.
How do you correctly set the PYTHONPATH variable on Windows?
Whenever I try to expirement with Python on Windows, I always run into a wall with the import statements. Python simply can’t find anything on Windows — every import, even for something as core as timezone fails.
I know this has something to do with the PYTHONPATH environment variable. In my case, Python is installed to «C:\Python27». My PYTHONPATH looks like this:
Still, nothing will import. I get errors like this:
What’s wrong with my situation?
3 Answers 3
Take a look at the official docs on using Python on Windows, in particular the section on finding modules.
You have to add the directory where you installed 3rd party modules to your PYTHONPATH if you didn’t install them to your Python27\Libs\site-packages directory.
Another option is to get acquainted with pip and virtualenv. These tools make installing 3rd party modules a breeze. Although I don’t know how well they are supported on Windows (I mainly do Python development on Linux).
PYTHONPATH = If this variable exists in your environment, Python will add it to the normal search path for modules when you use any import statement; you normally do not modify this as well behaved Python scripts will install themselves in the site-packages directory, and Python searches this by default.
PATH = this is the global file system path. Your operating system will search the directories listed in this variable (from left to right), to find commands when you type something at a command prompt.
In order for Python to work correctly only Windows, the C:\Python27 directory should be listed in PATH . If you ran the installer as an Administrator, the installer will modify the global PATH and add this for you. If you installed it as a normal user, you need to modify the PATH manually.
To add this manually, right click on My Computer and select Properties . Click on Advanced , then Environment Variables . You’ll see two boxes — User Variables and System Variables . You can only edit user variables — system variables need administrative access.
Simply add a new variable (or modify the existing PATH ) You should also add C:\Python27\Scripts to your PATH as most commands installed by Python scripts (like django-admin.py) are installed here. Directories are separated by ;
Once you have done this; python should work properly for you on Windows.
How to add to the PYTHONPATH in Windows, so it finds my modules/packages?
I have a directory which hosts all of my Django apps ( C:\My_Projects ). I want to add this directory to my PYTHONPATH so I can call the apps directly.
I tried adding C:\My_Projects\; to my Windows Path variable from the Windows GUI ( My Computer > Properties > Advanced System Settings > Environment Variables ). But it still doesn’t read the coltrane module and generates this error:
Error: No module named coltrane
22 Answers 22
You know what has worked for me really well on windows.
My Computer > Properties > Advanced System Settings > Environment Variables >
Just add the path as C:\Python27 (or wherever you installed python)
Then under system variables I create a new Variable called PythonPath . In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path
This is the best way that has worked for me which I hadn’t found in any of the docs offered.
EDIT: For those who are not able to get it, Please add
along with it. Else it will never work.
Windows 7 Professional I Modified @mongoose_za’s answer to make it easier to change the python version:
- [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
- Click [New] under «System Variable»
- Variable Name: PY_HOME, Variable Value:C:\path\to\python\version
- Click [OK]
- Locate the «Path» System variable and click [Edit]
Add the following to the existing variable:
%PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;
Click [OK] to close all of the windows.
As a final sanity check open a command prompt and enter python. You should see
If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.
From Windows command line:
To set the PYTHONPATH permanently, add the line to your autoexec.bat . Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.
Just append your installation path (ex. C:\Python27\) to the PATH variable in System variables. Then close and open your command line and type ‘python’.
These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:
That should take care of your problems
Adding Python and PythonPath to the Windows environment:
- Open Explorer.
- Right-click ‘Computer’ in the Navigation Tree Panel on the left.
- Select ‘Properties’ at the bottom of the Context Menu.
- Select ‘Advanced system settings’
- Click ‘Environment Variables. ‘ in the Advanced Tab
Under ‘System Variables’:
The easier way to set the path in python is : click start> My Computer >Properties > Advanced System Settings > Environment Variables > second windows >
select Path > Edit > and then add «;C:\Python27\;C:\Python27\Scripts\»
You need to add to your PYTHONPATH variable instead of Windows PATH variable.
The easiest way to do that successfully, is to run the python installer again (after the first installation) and then:
- choose Modify.
- check the optional features which you want and click Next.
- here we go, in «Advanced Options» step you must see an option saying «Add Python to environment variables». Just check that option and click Install.
When the installation is completed, python environment variables are added and you can easily use python everywhere.
You can also add a .pth file containing the desired directory in either your c:\PythonX.X folder, or your \site-packages folder , which tends to be my preferred method when I’m developing a Python package.
See here for more information.
This won’t persist over reboots or get translated to other files. It is however great if you don’t want to make a permanent modification to your system.
In Python 3.4 on windows it worked when I added it to PATH enviroment variable instead of PYTHONPATH. Like if you have installed Python 3.4 in D:\Programming\Python34 then add this at the end of your PATH environment variable
Close and reopen command prompt and execute ‘python’. It will open the python shell. This also fixed my Sublime 3 issue of ‘python is not recognized as an internal or external command’.
The python 2.X paths can be set from few of the above instructions. Python 3 by default will be installed in C:\Users\\AppData\Local\Programs\Python\Python35-32\ So this path has to be added to Path variable in windows environment.
The PYTHONPATH environment variable is used by Python to specify a list of directories that modules can be imported from on Windows. When running, you can inspect the sys.path variable to see which directories will be searched when you import something.
To set this variable from the Command Prompt, use: set PYTHONPATH=list;of;paths .
To set this variable from PowerShell, use: $env:PYTHONPATH=’list;of;paths’ just before you launch Python.
Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use. Read more in the Python on Windows FAQ docs.
To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.
This question needs a proper answer:
Just use the standard package site , which was made for this job!
and here is how (plagiating my own answer to my own question on the very same topic):
- Open a Python prompt and type
- Create this folder if it does not exist yet:
- Create a file sitecustomize.py in this folder containing the content of FIND_MY_PACKAGES , either manually or using something like the following code. Of course, you have to change C:\My_Projects to the correct path to your custom import location.
And the next time you start Python, C:\My_Projects is present in your sys.path , without having to touch system-wide settings. Bonus: the above steps work on Linux, too!
For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.
I got it worked in Windows 10 by following below steps.
Under environment variables, you should only add it under PATH of «System Variables» and not under «User Variables«. This is a great confusion and eats time if we miss it.
Also, just try to navigate to the path where you got Python installed in your machine and add it to PATH. This just works and no need to add any other thing in my case.I added just below path and it worked.
Most important, close command prompt, re-open and then re-try typing «python» to see the version details. You need to restart command prompt to see the version after setting up the path in environment variables.
After restarting, you should be able to see the python prompt and below info when typing python in command prompt: