Linux python script path

How to set Python environment variable PYTHONPATH on Linux?

Determine the path to your Python module or package. For example, suppose you have a Python module named mymodule located in the /home/user/myproject folder.

Set the PYTHONPATH environment variable to the path of your module or package using the following command −

$export PYTHONPATH=/home/user/myproject:$

This command sets the PYTHONPATH environment variable to /home/user/myproject and also includes the previous value of PYTHONPATH in case it was already set.

Note that the path should be separated by a colon (:) on Linux.

Verify that the PYTHONPATH environment variable has been set correctly using the following command −

This should display the path you set earlier, along with any previous paths that were included in PYTHONPATH.

Let us consider few more examples of setting the PYTHONPATH environment variable on Linux −

Set PYTHONPATH to a single path −

$export PYTHONPATH=/path/to/your/python/module

Set PYTHONPATH to multiple paths −

$export PYTHONPATH=/path/to/your/first/python/module:/path/to/your/second/python/module

Set PYTHONPATH to include the current directory −

$export PYTHONPATH=.:$PYTHONPATH

Set PYTHONPATH to include the current directory and a subdirectory −

$export PYTHONPATH=. /subdir:$PYTHONPATH

This sets the PYTHONPATH environment variable to include the current directory (.) and a subdirectory named subdir located in the current directory.

Note that the PYTHONPATH environment variable only affects the current shell session. If you want to set it permanently, you will need to add the export command to a startup script such as .bashrc or .bash_profile.

Determine the location of the folder containing the Python module or package that you want to add to the PYTHONPATH environment variable. For example, let’s say you have a folder called my_module located in your home directory (~/my_module).

Export the PYTHONPATH environment variable to include the folder containing the module or package, using the export command. For example, to add the ~/my_module folder to the PYTHONPATH environment variable, you can run the following command −

$export PYTHONPATH=$PYTHONPATH:~/my_module

The $PYTHONPATH variable is used to append the new folder to the existing value of PYTHONPATH, so that any previously set paths are not overwritten. The colon (:) is used to separate the new path from the existing paths.

Читайте также:  background-attachment

It must be noted that this command will only set the PYTHONPATH environment variable for the current terminal session. To make this setting permanent, you will need to add it to your shell’s configuration file (e.g., ~/.bashrc for Bash).

Verify that the PYTHONPATH environment variable has been set correctly. You can do this by running the following command −

This should display the current value of the PYTHONPATH environment variable, including the folder you just added.

Adding multiple folders to PYTHONPATH

$export PYTHONPATH=$PYTHONPATH:~/my_module:~/my_other_module

This will add both the ~/my_module and ~/my_other_module folders to the PYTHONPATH environment variable.

Adding a folder with a space in its path name −

$export PYTHONPATH=$PYTHONPATH:"/path/with/space/my_module"

Note the use of double quotes to enclose the path name containing spaces.

Adding a folder relative to the current directory −

$export PYTHONPATH=$PYTHONPATH:./my_module

This will add the my_module folder located in the current directory to the PYTHONPATH environment variable.

Setting PYTHONPATH to a specific folder only −

$export PYTHONPATH=/path/to/my_module

This will set the PYTHONPATH environment variable to only contain the my_module folder located at /path/to/.

By setting the PYTHONPATH environment variable, you can ensure that Python can find and import the modules and packages you need for your projects, even if they are located outside of the default search paths.

Adding a package that requires a specific version of Python −

$export PYTHONPATH=$PYTHONPATH:/path/to/my_package

If you have multiple versions of Python installed on your system and you want to use a package that requires a specific version, you can add the package’s location to the PYTHONPATH environment variable. This will allow you to use the package with the specific version of Python required.

For example, if you have Python 3.6 installed and a package that requires Python 3.7, you can add the package’s location to the PYTHONPATH environment variable for Python 3.6. Then, when you run Python 3.6, it will be able to find and import the package.

It must be noted that this approach is not a substitute for installing packages with the correct version of Python using a package manager like pip. Instead, it is a workaround for situations where you need to use a package that is not available for the version of Python you have installed.

These examples demonstrate the flexibility of the PYTHONPATH environment variable and how it can be used to customize the search path for Python modules and packages. By setting PYTHONPATH correctly, you can avoid errors related to module imports and ensure that your Python scripts and applications can access the modules and packages they need.

Читайте также:  Событие onsubmit

Источник

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

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

Получение Python

Платформа Windows

  • 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 устанавливается с помощью следующей команды из терминала.

 
sudo apt-get install python3-minimal

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

 
Extract the tarball tar xvfz Python-3.5.1.tgz Configure and Install: cd Python-3.5.1 ./configure --prefix = /opt/python3.5.1 make sudo make install

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 -

Примечание. 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 в командной строке.

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

 
$python # Unix/Linux or python% # Unix/Linux or C:>python # Windows/DOS

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

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 script.py # Unix/Linux or python% script.py # Unix/Linux or C:>python script.py # Windows/DOS

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

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

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

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

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

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

Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

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

По статье задано0 вопрос(ов)

Вам это нравится? Поделитесь в социальных сетях!

Источник

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