Pythonpath environment variable linux

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.

Читайте также:  Скопируйте файлы все файлы linux

Источник

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 со следующего сайта. Документация доступна в форматах HTML, PDF и PostScript.

Настройка 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

Он играет роль, подобную PATH. Эта переменная сообщает интерпретатору Python, где можно найти файлы модулей, импортированные в программу. Он должен включать каталог исходной библиотеки Python и каталоги, содержащие исходный код Python. PYTHONPATH иногда задается установщиком Python.

Он содержит путь к файлу инициализации, содержащему исходный код Python. Он выполняется каждый раз, когда вы запускаете интерпретатор. Он называется как .pythonrc.py в Unix и содержит команды, которые загружают утилиты или изменяют PYTHONPATH.

Он используется в Windows, чтобы проинструктировать Python о поиске первого нечувствительного к регистру совпадения в инструкции импорта. Установите эту переменную на любое значение, чтобы ее активировать.

Это альтернативный путь поиска модуля. Он обычно встроен в каталоги PYTHONSTARTUP или PYTHONPATH, чтобы упростить библиотеку модулей коммутации.

Читайте также:  Cmake linux install debian

Запуск Python

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

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

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

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

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

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

предоставлять отладочную информацию

генерировать оптимизированный байт-код (приводящий к .pyo-файлам)

не запускайте сайт импорта, чтобы искать пути Python при запуске

подробный вывод (подробная трассировка по операциям импорта)

отключить встроенные исключения на основе классов (просто используйте строки); устаревший, начиная с версии 1.6

запустить скрипт Python, отправленный в виде строки cmd

запустить скрипт Python из заданного файла

Скрипт из командной строки

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

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

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

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

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

Рекомендуем хостинг TIMEWEB

Рекомендуемые статьи по этой тематике

Источник

Understanding The Python Path Environment Variable in Python

Table of Contents

Environment variables influence the behavior of Python. PYTHONPATH is one such environment variable; that is, it is a key-value pair stored in a computer’s memory. It is available to all programs running in the same environment.В

Understanding the Pythonpath Environment Variable in

An environment variable that lets you add additional directories where Python looks for packages and modules. As these variables are not needed for Python to run, they are not set for most installations. Python can find its standard library. So, the only reason to use PYTHONPATH variables is to maintain directories of custom Python libraries that are not installed in the site packages directory (the global default location). In simple terms, it is used by user-defined modules to set the path so that they can be directly imported into a Python program. It also handles the default search path for modules in Python. PYTHONPATH variable includes various directories as a string to be added to the sys.path directory list. So, with PYTHONPATH, users can import modules that have not been made installable yet.В

Here is an example. The module sample.py has the following content:

В В В В print(«Function is running»)

The script sample_script.py has the following content:

Here is the output:

Traceback (most recent call last):

В В File «scripts/sample_script.py», line 1, in

В В В В import sample

ModuleNotFoundError: No module named ‘sample’

We get such an output because the PYTHONPATH has not been set yet. In layman’s terms, the Python interpreter cannot find the location of the sample.py file. In the next section, we will examine how you can set the PYTHONPATH environment variable on different operating systems.В

FREE Data Science With Python Course

Setting Python Environment Variable PYTHONPATH on Mac

To set the python environment variable PYTHONPATH on Mac, follow the given steps:

Step 1: Open the Terminal.

Step 2: In your text editor, open the

/.bash_profileВ file. For example: atomВ

Step 3: To this file, add the following line at the bottom:В

Step 4: Save this text editor file.

Step 5: Close the terminal.

Step 6: Restart the terminal. You can now read the new settings.В

Type: echo $PYTHONPATH

It would show something like /Users/my_user/code. That is it. PYTHONPATH is set.В

Setting the Python Environment Variable PYTHONPATH on Linux

To set the python environment variable PYTHONPATH on Linux, follow the given steps:

Step 1: Open up the terminalВ

Step 2: In your text editor, open the

/.bashrcВ file. For example: atomВ

Step 3: In this text editor, add this line at the end:

Step 4: Save this text editor file.

Step 5: Close the terminal applicationВ

Step 6: Restart the terminal application. You can read in the new settings. Type:

It will show something likeВ /home/my_user/code:В

You are done setting the PYTHONPATH on your Linux system.

Python Training Course

Setting the Python Environment Variable PYTHONPATH on Windows

Here is how to set PYTHONPATH on aВ windowsВ machine:В

Step 1:В Open My Computer or This PC and right-click on it. Then click on properties.

Step 2:В When the properties window pops up, click on the Advance System Settings.

Step 3:В Click on the environment variable button that appears in the new popped-up window. Here is how it looks:

Step 4:В In the dialog box- new Environment Variable, click on New.В

Step 5:В In the variable dialog box, add the variable’s name as PYTHONPATH. Add the location that you want Python to check every time as a value to the module directory.В

Free Course: Programming with Python

Step 6: Open the command prompt, execute the python file using the given command:В

(Here, my_script is the name of the python file).В

Looking forward to making a move to the programming field? Take up theВ Python Training CourseВ and begin your career as a professional Python programmer

Conclusion

We have reached the end of this blog. We saw how you could set the PYTHONPATH environment variable in Python on all three standard operating systems- Linux, Windows, and macOS. After setting up the PYTHON PATH, you can import user-defined modules. And if you wish to master Python, a certification in Python is all you need! However, if you wish to master full-stack development and build a successful career in this field, our PGP in Full Stack Development, in collaboration with Caltech CTME must be your next step.

And on the other hand, if you have any questions in terms of python path, do write to us in the comment section below, and our experts will get back to you!

Find our Python Training Online Classroom training classes in top cities:

S.No. Вариант и описание
1
Name Date Place
Python Training 13 Nov -5 Dec 2021,
Weekend batch
Your City View Details
Python Training 8 Jan -30 Jan 2022,
Weekend batch
Your City View Details

About the Author

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Источник

Читайте также:  What is windows 10 multiple editions
Оцените статью