- Adding installed PIP package to path automatically
- 2 Answers 2
- How I install python based scripts into system
- Updating the script
- naming with virtualenvwrapper
- alternative with tox
- Как добавить Python в переменную Windows PATH
- 2 min
- Зачем Добавлять Python В Windows PATH?
- Как Вручную Добавить Python В ПУТЬ Windows
- Найдите Путь Установки Python На Вашем ПК
- Далее: Добавить Python В PATH В Пользовательских Переменных
- Добавление Python В PATH С Помощью Параметра Системных Переменных
- Добавить Python В Windows PATH Автоматически
- Подтвердите, Что Python Добавлен В Windows PATH
- 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!
Adding installed PIP package to path automatically
For my package, foo, I’m using the following setup.py:
When testing on my Arch system, it added the script to PATH automatically so I could just run foo on my command line and it’d run the function main() automatically. Then, I booted up a VM and tested it on Windows 7. Pip installed the package just fine, but it wasn’t in my path!
2 Answers 2
setuptools , pip and easy_install don’t modify the system PATH variable. The
\Scripts directory, where all of them install the script by default, is normally added to PATH by the Python installer during installation.
If the scripts folder was not added to your PATH during installation, you can fix that by running
The above sample setup.py file worked fine for me (with the Scripts directory in PATH), by the way. I tested it with
Do not expect pip or easy_install to modify your PATH , their task is to install a package into current environment.
On Linux, if you use global Python environment, you are likely to need root privileges, so you typically do:
However, this is not recommended method as it spoils system-wide Python environment (imagine having two applications having a bit different requirements to the same package version and you might have a problem).
Recommended method is to use some sort of virtualenv, which allows installing python package into separate python environment, which is also easy to remove and recreate.
How I install python based scripts into system
It seems like you have custom python based script, which you want to use in your system.
For this scenario I use following method (assuming virtualenv tool is installed into system-wide python):
Now you shall have in
/apps/myutil/.env/bin directory installed all the script installed by pip , let us call it myscript (there can be more).
Remaining step is to make symlink from some directory which is already on PATH , e.g. into /usr/local/bin :
From now on, you shall be able calling command myscript even without virtualenv being activated.
Updating the script
If you need to install later version of the script:
As you have the script linked, it will automatically be available in the latest version.
naming with virtualenvwrapper
virtualenvwrapper allows you to create multiple named virtualenvs and give you easy activation and deactivation. In such case I do the following:
Upgrade is even simpler:
and you are done
alternative with tox
tox is great tool for automated creation of virtualenvs and testing. I use it for creating virtualenvs in directories I like. For more information see my other SO answer
Как добавить Python в переменную Windows PATH
2 min
Запуск Python с терминала зачастую неизбежен. Однако, если вы впервые установили Python в Windows 10, запуск его через Терминал Windows возможен только в том случае, если он добавлен в переменную среды Windows PATH.
Это может показаться сложным, но бояться нечего. Чтобы помочь вам преодолеть повороты, связанные с добавлением Python в PATH Windows после его установки, давайте рассмотрим варианты и несколько необходимых шагов.
Зачем Добавлять Python В Windows PATH?
Если вам не удалось добавить Python в PATH в вашей ОС Windows, вы не сможете запустить интерпретатор Python, запустить виртуальную среду программирования или выполнить такие команды, как pip install, из терминала.
Мы исследуем лучшие способы создания виртуальных сред Python и управления ими.
Это потому, что, когда вы запускаете любую программу, отличную от программы по умолчанию, из командной строки, машина ищет исполняемый файл в текущей папке или в ПУТИ Windows.
Если его нет в переменной PATH, терминал возвращает ошибку «команда не найдена». Добавление в PATH – это мощный инструмент, даже если вы выполняете команду из созданного или пакетного файла по умолчанию , добавление родительского исполняемого файла в переменную PATH также делает его доступным для вызова из терминала.
Как Вручную Добавить Python В ПУТЬ Windows
Во-первых, если вы не установили Python на свой компьютер, перейдите на веб- сайт python.org, чтобы загрузить и установить предпочитаемую версию.
После успешной установки Python на ваш компьютер проверьте, не добавлен ли он в PATH Windows. Откройте свой терминал и введите python , затем нажмите клавишу Enter . Команда может вернуть ошибку, в которой говорится, что «python не распознается как внутренняя или внешняя команда, работающая программа или пакетный файл», что означает, что Python еще не добавлен в переменную PATH вашего компьютера.
Чтобы запускать программы Python из командной строки, выполните шаги, выделенные ниже.
Найдите Путь Установки Python На Вашем ПК
Чтобы добавить Python в ваш Windows PATH, вам нужно получить путь его установки. Для этого откройте панель поиска Windows и введите python.exe (не нажимайте клавишу Enter ). Затем щелкните правой кнопкой мыши Python.exe, который появляется в появившемся меню, и выберите опцию Открыть расположение файла .
В открывшихся окнах проводника щелкните длинную панель каталогов слева от строки поиска. Выделите и скопируйте весь текст пути в буфер обмена с помощью Ctrl + c . Затем перейдите к следующим шагам ниже.
Далее: Добавить Python В PATH В Пользовательских Переменных
Чтобы добавить Python в PATH в пользовательских переменных , щелкните правой кнопкой мыши « Этот компьютер» и выберите « Свойства» . Оказавшись в меню свойств, нажмите на опцию Advanced system settings . В следующем окне выберите вкладку Advanced и выберите Environment Variables .
Environment Variables меню состоит из двух отдельных частей: верхняя часть называется Пользовательские переменные , а нижняя часть имени системных переменных . Однако в этом случае мы сосредоточимся на пользовательских переменных .
В меню пользовательских переменных найдите переменную с именем Path . Затем вставьте путь, который вы скопировали ранее, в параметр «Значение переменной», используя Ctrl + v, и нажмите « ОК» .
Однако, если вы не можете найти эту переменную, вам может потребоваться ее создать. Для этого нажмите New . Затем в форме имени переменной введите путь и вставьте свой путь Python в поле значения переменной .
Вернитесь в папку пути установки Python и дважды щелкните Scripts, чтобы открыть этот каталог. Затем скопируйте его путь из панели пути в верхней части окон (помимо панели поиска), как вы это делали ранее для пути установки Python.
Скопировав путь к скриптам, вернитесь к переменным среды . Затем выберите переменную Path и нажмите Edit . Введите точку с запятой после пути к исполняемому файлу Python и вставьте после него путь скриптов, который вы только что скопировали. Затем нажмите ОК .
Добавление Python В PATH С Помощью Параметра Системных Переменных
Вы также можете добавить Python в системную переменную PATH. Хотя это всего лишь альтернатива, и в ней нет необходимости, если вы уже добавили ее в переменные Users .
Чтобы использовать параметр « Системные переменные» , выполните шаги, выделенные выше, для копирования пути Python и его сценария. Затем вернитесь в переменные среды . Затем в сегменте системных переменных найдите переменную с именем Path . Щелкните эту переменную и щелкните Изменить .
В следующем появившемся окне нажмите New и вставьте путь, который вы скопировали ранее, в открывшееся пространство. Повторите этот процесс и для пути скриптов . Затем нажмите ОК и закройте окно переменных среды .
Добавить Python В Windows PATH Автоматически
Вы также можете автоматически добавить Python в PATH Windows во время установки. Хотя этот метод работает не во всех случаях, вы все равно можете попробовать.
Для этого щелкните свой установочный файл и установите флажок « Добавить Python 3.7 в PATH» . Номер версии будет меняться при установке разных версий Python.
Установка этого флажка автоматически добавляет Python в ваш путь к Windows. Это означает, что вы можете запускать команды Python через командную строку сразу после установки.
Подтвердите, Что Python Добавлен В Windows PATH
Чтобы узнать, добавлен ли Python в PATH Windows, откройте терминал и введите python –version , затем нажмите клавишу Enter . Если команда возвращает текущую установленную версию Python, это означает, что вы успешно добавили ее в Windows PATH.
Однако, чтобы проверить, добавили ли вы каталог Scripts в Windows PATH, попробуйте запустить пакет установки pip на терминале, заменив «package» на предпочитаемую вами библиотеку. Если вы установили Python 2.7.9 и выше, команда устанавливает названный пакет, указывая, что вы также успешно добавили скрипты Python в путь.
Помимо добавления Python в PATH Windows, вы можете добавить текстовые редакторы, интегрированные среды разработки (IDE), Git, Node, Anaconda и многие другие программы.
Например, управлять проектом с помощью Sublime Text легко, когда вы открываете терминал в каталоге папки вашего проекта и запускаете subl. команда. Это откроет редактор в вашей текущей папке и отобразит его на боковой панели, еще один экономящий время ярлык для продуктивной работы с Sublime Text .
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: