Перейти к содержимому

Как изменить path python

  • автор:

Python 3 — Урок 002. Настройка среды

Python 3 доступен для Windows, Mac OS и большинства вариантов операционной системы Linux.

Настройка локальной среды

Откройте окно терминала и введите «python», чтобы узнать, установлен ли он и какая версия установлена.

Получение Python

Платформа Windows

Бинарники последней версии Python 3 (Python 3.6.4) доступны на этой странице загрузки

Доступны следующие варианты установки.

  • Windows x86-64 embeddable zip file
  • Windows x86-64 executable installer
  • Windows x86-64 web-based installer
  • Windows x86 embeddable zip file
  • Windows x86 executable installer
  • Windows x86 web-based installer

Примечание. Для установки Python 3.6.4 минимальными требованиями к ОС являются Windows 7 с пакетом обновления 1 (SP1). Для версий от 3.0 до 3.4.x Windows XP является приемлемым.

Платформа Linux

Различные варианты использования Linux используют разные менеджеры пакетов для установки новых пакетов.

На Ubuntu Linux Python 3 устанавливается с помощью следующей команды из терминала.

Установка из исходников

Загрузите исходный tar-файл Gzipped с URL-адреса загрузки Python https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz

Mac OS

Загрузите установщики Mac OS с этого URL-адреса https://www.python.org/downloads/mac-osx/

Дважды щелкните этот файл пакета и следуйте инструкциям мастера для установки.

Самый современный и текущий исходный код, двоичные файлы, документация, новости и т.д. Доступны на официальном сайте Python —

Python Official Website − https://www.python.org/

Вы можете загрузить документацию Python со следующего сайта. Документация доступна в форматах HTML, PDF и PostScript.

Python Documentation Website − www.python.org/doc/

Настройка PATH

Программы и другие исполняемые файлы могут быть во многих каталогах. Следовательно, операционные системы предоставляют путь поиска, в котором перечислены каталоги, которые он ищет для исполняемых файлов.

Важными особенностями являются:

  • Путь хранится в переменной среды, которая является именованной строкой, поддерживаемой операционной системой. Эта переменная содержит информацию, доступную для командной оболочки и других программ.
  • Переменная пути называется PATH в Unix или Path в Windows (Unix чувствительна к регистру, Windows — нет).
  • В Mac OS установщик обрабатывает детали пути. Чтобы вызвать интерпретатор Python из любого конкретного каталога, вы должны добавить каталог Python на свой путь.

Настройка PATH в Unix / Linux

Чтобы добавить каталог Python в путь для определенного сеанса в Unix —

  • В csh shell — введите setenv PATH «$ PATH:/usr/local/bin/python3» и нажмите Enter.
  • В оболочке bash (Linux) — введите PYTHONPATH=/usr/local/bin/python3.4 и нажмите Enter.
  • В оболочке sh или ksh — введите PATH = «$PATH:/usr/local/bin/python3» и нажмите Enter.

Примечание. /usr/local/bin/python3 — это путь к каталогу Python.

Настройка PATH в Windows

Чтобы добавить каталог Python в путь для определенного сеанса в Windows —

  • В командной строке введите путь %path%;C:\Python и нажмите Enter.

Примечание. C:\Python — это путь к каталогу Python.

Переменные среды Python

S.No. Переменная и описание
1 PYTHONPATH Он играет роль, подобную PATH. Эта переменная сообщает интерпретатору Python, где можно найти файлы модулей, импортированные в программу. Он должен включать каталог исходной библиотеки Python и каталоги, содержащие исходный код Python. PYTHONPATH иногда задается установщиком Python.
2 PYTHONSTARTUP Он содержит путь к файлу инициализации, содержащему исходный код Python. Он выполняется каждый раз, когда вы запускаете интерпретатор. Он называется как .pythonrc.py в Unix и содержит команды, которые загружают утилиты или изменяют PYTHONPATH.
3 PYTHONCASEOK Он используется в Windows, чтобы проинструктировать Python о поиске первого нечувствительного к регистру совпадения в инструкции импорта. Установите эту переменную на любое значение, чтобы ее активировать.
4 PYTHONHOME Это альтернативный путь поиска модуля. Он обычно встроен в каталоги PYTHONSTARTUP или PYTHONPATH, чтобы упростить библиотеку модулей коммутации.

Запуск Python

Существует три разных способа запуска Python —

Интерактивный интерпретатор

Вы можете запустить Python из Unix, DOS или любой другой системы, которая предоставляет вам интерпретатор командной строки или окно оболочки.

Введите python в командной строке.

Начните кодирование сразу в интерактивном интерпретаторе.

Вот список всех доступных параметров командной строки —

S.No. Вариант и описание
1 -d предоставлять отладочную информацию
2 -O генерировать оптимизированный байт-код (приводящий к .pyo-файлам)
3 -S не запускайте сайт импорта, чтобы искать пути Python при запуске
4 -v подробный вывод (подробная трассировка по операциям импорта)
5 -X отключить встроенные исключения на основе классов (просто используйте строки); устаревший, начиная с версии 1.6
6 -c cmd запустить скрипт Python, отправленный в виде строки cmd
7 file запустить скрипт Python из заданного файла
Скрипт из командной строки

Сценарий Python можно запустить в командной строке, вызвав интерпретатор в вашем приложении, как показано в следующем примере.

Примечание. Убедитесь, что права файлов разрешают выполнение.

Интегрированная среда разработки

Вы можете запустить Python из среды графического интерфейса пользователя (GUI), если у вас есть приложение GUI в вашей системе, которое поддерживает Python.

Для разработки Python приложений рекомендую PyCharm от компании JetBrains, как наиболее развитую и удобную IDE.

Изменение пути поиска в Python

Когда интерпретатор Python выполняет оператор import , он ищет как код Python, так и модули расширения по пути поиска. Значение по умолчанию для пути настраивается в двоичном файле Python при сборке интерпретатора. Вы можете определить путь, импортировав модуль sys и напечатав значение sys.path .

Нулевая строка в sys.path представляет текущий рабочий каталог.

Ожидаемое соглашение для локально установленных пакетов состоит в том, чтобы поместить их в каталог . /site-packages/ , но вы можете захотеть установить модули Python в какой-нибудь произвольный каталог. Например, на вашем сайте может быть принято соглашение о хранении всего программного обеспечения, связанного с веб-сервером, в каталоге /www . Дополнительные модули Python могут принадлежать /www/python , и для их импорта этот каталог должен быть добавлен в sys.path . Существует несколько различных способов добавления каталога.

Самый удобный способ — добавить файл конфигурации пути в каталог, который уже указан в пути Python, обычно в каталог . /site-packages/ . Файлы конфигурации пути имеют расширение .pth , и каждая строка должна содержать один путь, который будет добавлен к sys.path . (Поскольку новые пути добавляются к sys.path , модули в добавленных каталогах не будут переопределять стандартные модули. Это означает, что вы не можете использовать этот механизм для установки фиксированных версий стандартных модулей.)

Пути могут быть абсолютными или относительными, и в этом случае они относятся к каталогу, содержащему файл .pth .Дополнительную информацию см. в документации модуля site .

Чуть менее удобный способ — отредактировать файл site.py в стандартной библиотеке Python и изменить sys.path . site.py автоматически импортируется при выполнении интерпретатора Python, если только параметр -S не указан для подавления этого поведения. Таким образом, вы можете просто отредактировать site.py и добавить в него две строки:

Однако, если вы переустановите ту же основную версию Python (например, при обновлении с 2.2 до 2.2.2), site.py будет перезаписан стандартной версией. Вы должны помнить, что он был изменен, и сохранить копию перед установкой.

Есть две переменные среды, которые могут изменять sys.path . PYTHONHOME устанавливает альтернативное значение для префикса установки Python. Например, если PYTHONHOME задано значение /www/python , путь поиска будет иметь значение [», ‘/www/python/lib/pythonX.Y/’, ‘/www/python/lib/pythonX.Y/plat-linux2’, . ] .

В переменной PYTHONPATH можно указать список путей, которые будут добавлены в начало sys.path . Например, если для PYTHONPATH установлено значение /www/python:/opt/py , путь поиска будет начинаться с [‘/www/python’, ‘/opt/py’] . (Обратите внимание, что каталоги должны существовать, чтобы их можно было добавить в sys.path ; модуль site удаляет несуществующие пути.)

Наконец, sys.path — это обычный список Python, поэтому любое приложение Python может изменять его, добавляя или удаляя записи.

Файлы конфигурации Distutils

Как упоминалось выше,вы можете использовать конфигурационные файлы Distutils для записи личных предпочтений или предпочтений сайта для любых опций Distutils.То есть,любой параметр любой команды может быть сохранен в одном из двух или трех (в зависимости от вашей платформы)конфигурационных файлов,которые будут просмотрены перед разбором командной строки.Это означает,что конфигурационные файлы отменяют значения по умолчанию,а командная строка,в свою очередь,отменяет конфигурационные файлы.Более того,если используется несколько конфигурационных файлов,значения из «более ранних» файлов отменяются «более поздними» файлами.

Расположение и имена файлов конфигурации

Имена и расположение конфигурационных файлов немного отличаются на разных платформах.На Unix и macOS три конфигурационных файла (в порядке их обработки)следующие:

How to Add Python to PATH

You may need to add Python to PATH if you’ve installed Python, but typing python on the command line doesn’t seem to work. You may be getting a message saying that the term python isn’t recognized, or you may end up with the wrong version of Python running.

A common fix for these problems is adding Python to the PATH environment variable. In this tutorial, you’ll learn how to add Python to PATH . You’ll also learn about what PATH is and why PATH is vital for programs like the command line to be able to find your Python installation.

Note: A path is the address of a file or folder on your hard drive. The PATH environment variable, also referred to as just PATH or Path, is a list of paths to directories that your operating system keeps and uses to find executable scripts and programs.

The steps that you’ll need to take to add something to PATH will depend significantly on your operating system (OS), so be sure to skip to the relevant section if you’re only interested in this procedure for one OS.

Note that you can use the following steps to add any program to PATH , not just Python.

Supplemental Code: Click here to download free supplemental code that’ll walk you through changing PATH across operating systems.

How to Add Python to PATH on Windows

The first step is to locate the directory in which your target Python executable lives. The path to the directory is what you’ll be adding to the PATH environment variable.

To find the Python executable, you’ll need to look for a file called python.exe . The Python executable could be in a directory in C:\Python\ or in your AppData\ folder, for instance. If the executable were in AppData\ , then the path would typically look something like this:

In your case, the <USER> part would be replaced by your currently logged-in user name.

Once you’ve found the executable, make sure it works by double-clicking it and verifying that it starts up a Python REPL in a new window.

If you’re struggling to find the right executable, you can use Windows Explorer’s search feature. The issue with the built-in search is that it’s painfully slow. To perform a super-fast full system search for any file, a great alternative is Everything:

A screenshot of the Everything program searching for "python.exe"

Those paths highlighted in yellow, namely those at \WindowsApps and \Python310 , would be ideal candidates to add to PATH because they look like executables at the root level of an installation. Those highlighted in red wouldn’t be suitable because some are part of a virtual environment—you can see venv in the path—and some are shortcuts or internal Windows installations.

You may also encounter Python executables that are installed within the folder for a different program. This is due to the fact that many applications bundle their own version of Python within them. These bundled Python installations would also be unsuitable.

Once you’ve located your Python executable, open the Start menu and search for the Edit the system environment variables entry, which opens up a System Properties window. In the Advanced tab, click on the button Environment Variables. There you’ll see User and System variables, which you’ll be able to edit:

In the section entitled User Variables, double-click on the entry that says Path. Another window will pop up showing a list of paths. Click the New button and paste the path to your Python executable there. Once that’s inserted, select your newly added path and click the Move Up button until it’s at the top.

That’s it! You may need to reboot your computer for the changes to take effect, but you should now be able to call python from the command line.

For setting the PATH environment variable from the command line, check out the section on Configuring Environment Variables in the Windows Python coding setup guide. You can also find instructions in the supplemental materials:

Supplemental Code: Click here to download free supplemental code that’ll walk you through changing PATH across operating systems.

You may also want to set up PATH on your Linux or macOS machine, or perhaps you’re using Windows Subsystem for Linux (WSL). If so, read the next section for the procedure on UNIX-based systems.

How to Add Python to PATH on Linux and macOS

Since Python typically comes pre-installed on UNIX-based systems, the most common problem on Linux and macOS is for the wrong python to run, rather than not finding any python . That said, in this section, you’ll be troubleshooting not being able to run python at all.

Note: Depending on your particular system, you may have a python program for Python 2, and a python3 for Python 3. In other instances, both python and python3 will point to the same executable.

The first step is locating your target Python executable. It should be a program that you can run by first navigating to the containing directory and then typing ./python on the command line.

You need to prepend the call to the Python executable with its relative path in the current folder ( ./ ) because otherwise you’ll invoke whichever Python is currently recorded on your PATH . As you learned earlier, this might not be the Python interpreter that you want to run.

Often the Python executable can be found in the /bin/ folder. But if Python is already in the /bin/ folder, then it’s most likely already on PATH because /bin/ is automatically added by the system. If this is the case, then you may want to skip to the section on the order of paths within PATH .

Since you’re probably here because you’ve installed Python but it’s still not being found when you type python on the command line, though, you’ll want to search for it in another location.

Note: A great search utility for quickly searching large folders is fzf. It works from the command line and will search all files and folders within your current working directory. So you might search for python from your home directory, for instance. fzf will then show you the paths that contain python .

That said, it might be that /bin/ has been removed from PATH altogether, in which case you might skip forward to the section on mangaging PATH .

Once you’ve located your Python executable and are sure it’s working, take note of the path for later. Now it’s time to start the process of adding it to your PATH environment variable.

First, you’ll want to navigate to your home folder to check out what configuration scripts you have available:

You should see a bunch of configuration files that begin with a period ( . ). These are colloquially known as dotfiles and are hidden from ls by default.

One or two dotfiles get executed whenever you log in to your system, another one or two run whenever you start a new command-line session, and most others are used by other applications for configuration settings.

You’re looking for the files that run when you start your system or a new command-line session. They’ll probably have names similar to these:

  • .profile
  • .bash_profile
  • .bash_login
  • .zprofile
  • .zlogin

The keywords to look for are profile and login. You should, in theory, only have one of these, but if you have more than one, you may need to read the comments in them to figure out which ones run on login. For example, .profile file on Ubuntu will typically have the following comment:

So, if you have .profile but also .bash_profile , then you’ll want to use .bash_profile .

You can also use a .bashrc or .zshrc file, which are scripts that run whenever you start a new command-line session. Run command (rc) files are common places to put PATH configurations.

Note: Pedantically speaking, rc files are generally for settings that affect the look and feel of your command-line prompt, not for configuring environment variables like PATH . But you can use rc files for your PATH configuration if you prefer.

To add the Python path to the beginning of your PATH environment variable, you’re going to be executing a single command on the command line.

Use the following line, replacing <PATH_TO_PYTHON> with your actual path to the Python executable, and replace .profile with the login script for your system:

This command adds export PATH=»<PATH_TO_PYTHON>:$PATH» to the end of .profile . The command export PATH=»<PATH_TO_PYTHON>:$PATH» prepends <PATH_TO_PYTHON> to the PATH environment variable. It’s similar to the following operation in Python:

Since PATH is just a string separated by colons, prepending a value involves creating a string with the new path, a colon, then the old path. With this string, you set the new value of PATH .

To refresh your current command-line session, you can run the following command, replacing .profile with whichever login script you’ve chosen:

Now, you should be able to call python from the command line directly. The next time you log in, Python should automatically be added to PATH .

If you’re thinking this process seems a bit opaque, you’re not alone! Read on for more of a deep dive into what’s going on.

Understanding What PATH Is

PATH is an environment variable that contains a list of paths to folders. Each path in PATH is separated by a colon or a semicolon—a colon for UNIX-based systems and a semicolon for Windows. It’s like a Python variable with a long string as its value. The difference is that PATH is a variable accessible by almost all programs.

Programs like the command line use the PATH environment variable to find executables. For example, whenever you type the name of a program into the command line, the command line will search various places for the program. One of the places that the command line searches is PATH .

All the paths in PATH need to be directories—they shouldn’t be files or executables directly. Programs that use PATH take each directory in turn and search all the files within it. Subdirectories within directories in PATH don’t get searched, though. So it’s no good just adding your root path to PATH !

It’s also important to note that programs that use PATH typically don’t search for anything except executables. So, you can’t use PATH as a way to define shortcuts to commonly used files.

Understanding the Importance of Order Within PATH

If you type python into the command line, the command line will look in each folder in the PATH environment variable for a python executable. Once it finds one, it’ll stop searching. This is why you prepend the path to your Python executable to PATH . Having the newly added path first ensures that your system will find this Python executable.

A common issue is having a failed Python installation on your PATH . If the corrupted executable is the first one that the command line comes across, then the command line will try and run that and then abort any further searching. The quick fix for this is just adding your new Python directory before the old Python directory, though you’d probably want to clean your system of the bad Python installation too.

Reordering PATH on Windows is relatively straightforward. You open the GUI control panel and adjust the order using the Move Up and Move Down buttons. If you’re on a UNIX-based operating system, however, the process is more involved. Read on to learn more.

Managing Your PATH on UNIX-based Systems

Usually, your first task when managing your PATH is to see what’s in there. To see the value of any environment variable in Linux or macOS, you can use the echo command:

Note that the $ symbol is used to tell the command line that the following identifier is a variable. The issue with this command is that it just dumps all the paths on one line, separated by colons. So you might want to take advantage of the tr command to translate colons into newlines:

In this example, you can see that badpython is present in PATH . The ideal course of action would be to perform some PATH archaeology and figure out where it gets added to PATH , but for now, you just want to remove it by adding something to your login script .

Since PATH is a shell string, you don’t have access to convenient methods to remove parts of it, like you would if it were a Python list. That said, you can pipe together a few shell commands to achieve something similar:

This command takes the list from the previous command and feeds it into grep , which, together with the -v switch, will filter out any lines containing the substring badpython . Then you can translate the newlines back to colons, and you have a new and valid PATH string that you use right away to replace your old PATH string.

Though this can be a handy command, the ideal solution would be to figure out where that bad path gets added. You could try looking at other login scripts or examine specific files in /etc/ . In Ubuntu, for instance, there’s a file called environment , which typically defines a starting path for the system. In macOS, that might be /etc/paths . There can also be profile files and folders in /etc/ that might contain startup scripts.

The main difference between configurations in /etc/ and in your home folder is that what’s in /etc/ is system-wide, while whatever’s in your home folder will be scoped to your user.

It can often involve a bit of archeology to track down where something gets added to your PATH , though. So, you may want to add a line in your login or rc script that filters out certain entries from PATH as a quick fix.

Conclusion

In this tutorial, you’ve learned how to add Python, or any other program, to your PATH environment variable on Windows, Linux, and macOS. You also learned a bit more about what PATH is and why its internal order is vital to consider. Finally, you also discovered how you might manage your PATH on a UNIX-based system, seeing as it’s more complex than managing your PATH on Windows.

Supplemental Code: Click here to download free supplemental code that’ll walk you through changing PATH across operating systems.

Using PYTHONPATH¶

The PYTHONPATH variable has a value that is a string with a list of directories that Python should add to the sys.path directory list.

The main use of PYTHONPATH is when we are developing some code that we want to be able to import from Python, but that we have not yet made into an installable Python package (see: making a Python package ).

Returning to the example module and script in Where does Python look for modules? :

At the moment, on my machine, PYTHONPATH is empty:

Before we set PYTHONPATH correctly, a_script.py will fail with:

Now I set the PYTHONPATH environment variable value to be the path to the code directory:

Setting PYTHONPATH more permanently¶

You probably don’t want to have to set PYTHONPATH every time you start up a terminal and run a Python script.

Luckily, we can make the PYTHONPATH value be set for any terminal session, by setting the environment variable default.

For example, let’s say I wanted add the directory /Users/my_user/code to the PYTHONPATH:

If you are on a Mac¶

/.bash_profile in your text editor – e.g. atom

Add the following line to the end:

Start Terminal.app again, to read in the new settings, and type this:

It should show something like /Users/my_user/code .

If you are on Linux¶

Open your favorite terminal program;

/.bashrc in your text editor – e.g. atom

Add the following line to the end:

Close your terminal application;

Start your terminal application again, to read in the new settings, and type this:

It should show something like /home/my_user/code .

If you are on Windows¶

Got to the Windows menu, right-click on “Computer” and select “Properties”:

From the computer properties dialog, select “Advanced system settings” on the left:

From the advanced system settings dialog, choose the “Environment variables” button:

In the Environment variables dialog, click the “New” button in the top half of the dialog, to make a new user variable:

Give the variable name as PYTHONPATH and the value is the path to the code directory. Choose OK and OK again to save this variable.

Now open a cmd Window (Windows key, then type cmd and press Return). Type:

to confirm the environment variable is correctly set.

If you want your IPython sessions to see this new PYTHONPATH variable, you’ll have to restart your terminal and restart IPython so that it picks up PYTHONPATH from the environment settings.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *