Adding python path 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.
Читайте также:  Printmanagement msc windows server 2012

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

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

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

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

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

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

Запуск Python

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

How to add python path in Ubuntu 16.04

I’m trying to run a scrapy project on a ubuntu server. For which I need to add the project path to python path.

I created a .bash_profile file in the /home directory with the following contents:

But I’m getting error running my python file stating it didn’t find the module.

I tried using the following paths, but nothing works.

  • /home/john/Desktop/myscraper/
  • /home/john/Desktop/myscraper
  • home/john/Desktop/myscraper/
  • home/john/Desktop/myscraper

2 Answers 2

Ubuntu does not use

/.bash_profile by default. You should use

The path you should use is /home/john/Desktop/myscraper , though /home/john/Desktop/myscraper/ would also work. Paths that don’t start with slashes are relative, not absolute, so will not work unless the working directory is / . More details here on Wikipedia.

You can put the definition and export statements together, and if PYTHONPATH is not already defined, you can leave off the $PYTHONPATH: at the start.

Config files belong in your personal home directory ( /home/$USER , $HOME or simply

), not in the /home directory. In your case that will be /home/john .

Please also make sure to use the correct casing, it’s export in all lowercase.

Since export is not accessing but referencing the variable, you do not use the $ sign: export PYTHONPATH

Are you sure you want to have this in your .bash_profile and not your .bashrc ? You can read up on the difference here.

In any case you will have to run source

./bash_profile (or source

./bashrc if you go with that) for your changes to take effect.

Источник

PYTHONPATH on Linux [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 6 years ago .

I’m novice in this, and I have started learning Python, but I have some questions that I’m not be able to understand,

  1. What exactly is the PYTHONPATH (on Ubuntu)? Is it a folder?
  2. Is Python provided by default on Ubuntu, or does it have to be installed explicitly?
  3. Where is the folder in which all modules are (I have a lot folders called python_ )?
  4. If I wish a new module to work when I’m programming (such as pyopengl) where should I go to introduce all the folders I’ve got in the folder downloaded?
  5. Coming back from the PYTHONPATH issue, how do I configure the PYTHONPATH in order to start working on my new module?

3 Answers 3

1) PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

Here I use the sh syntax. For other shells (e.g. csh , tcsh ), the syntax would be slightly different. To make it permanent, set the variable in your shell’s init file (usually

2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I’ve found that to be rarely necessary.

3) The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn’t care about where it lives — Python knows where it is and it can find the modules. Sort of like issuing the command ls — where does ls live? /usr/bin ? /bin ? 99% of the time, you don’t need to care — Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

4) I’m not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn’t have to care about where it got installed.

5) Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

Источник

Permanently add a directory to PYTHONPATH?

Whenever I use sys.path.append , the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH ?

20 Answers 20

If you’re using bash (on a Mac or GNU/Linux distro), add this to your

/.bashrc then run source

You need to add your new directory to the environment variable PYTHONPATH , separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you’re using ( .profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

superuser.com may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it’s not really a programming question per se.

Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

For some reason this doesn’t seem to work in Python 2.7. There you can use:

Then create a .pth file in that directory containing the path you want to add (create the directory if it doesn’t exist).

This works on Windows

  1. On Windows, with Python 2.7 go to the Python setup folder.
  2. Open Lib/site-packages.
  3. Add an example.pth empty file to this folder.
  4. Add the required path to the file, one per each line.

Then you’ll be able to see all modules within those paths from your scripts.

In case anyone is still confused — if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you’re done

You could add the path via your pythonrc file, which defaults to

/.pythonrc on linux. ie.

You could also set the PYTHONPATH environment variable, in a global rc file, such

/.profile on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.

Источник

Читайте также:  Виртуальные жесткие диски linux
Оцените статью
S.No. Вариант и описание
1