Mac os python site packages

5. Using Python on a MacВ¶

Python on a Mac running macOS is in principle very similar to Python on any other Unix platform, but there are a number of additional features such as the IDE and the Package Manager that are worth pointing out.

5.1. Getting and Installing MacPythonВ¶

macOS since version 10.8 comes with Python 2.7 pre-installed by Apple. If you wish, you are invited to install the most recent version of Python 3 from the Python website (https://www.python.org). A current “universal binary” build of Python, which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there.

What you get after installing is a number of things:

A Python 3.9 folder in your Applications folder. In here you find IDLE, the development environment that is a standard part of official Python distributions; and PythonLauncher, which handles double-clicking Python scripts from the Finder.

A framework /Library/Frameworks/Python.framework , which includes the Python executable and libraries. The installer adds this location to your shell path. To uninstall MacPython, you can simply remove these three things. A symlink to the Python executable is placed in /usr/local/bin/.

The Apple-provided build of Python is installed in /System/Library/Frameworks/Python.framework and /usr/bin/python , respectively. You should never modify or delete these, as they are Apple-controlled and are used by Apple- or third-party software. Remember that if you choose to install a newer Python version from python.org, you will have two different but functional Python installations on your computer, so it will be important that your paths and usages are consistent with what you want to do.

IDLE includes a help menu that allows you to access Python documentation. If you are completely new to Python you should start reading the tutorial introduction in that document.

If you are familiar with Python on other Unix platforms you should read the section on running Python scripts from the Unix shell.

5.1.1. How to run a Python scriptВ¶

Your best way to get started with Python on macOS is through the IDLE integrated development environment, see section The IDE and use the Help menu when the IDE is running.

If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script. macOS comes with a number of standard Unix command line editors, vim and emacs among them. If you want a more Mac-like editor, BBEdit or TextWrangler from Bare Bones Software (see http://www.barebones.com/products/bbedit/index.html) are good choices, as is TextMate (see https://macromates.com/). Other editors include Gvim (http://macvim-dev.github.io/macvim/) and Aquamacs (http://aquamacs.org/).

To run your script from the Terminal window you must make sure that /usr/local/bin is in your shell search path.

To run your script from the Finder you have two options:

Drag it to PythonLauncher

Select PythonLauncher as the default application to open your script (or any .py script) through the finder Info window and double-click it. PythonLauncher has various preferences to control how your script is launched. Option-dragging allows you to change these for one invocation, or use its Preferences menu to change things globally.

5.1.2. Running scripts with a GUIВ¶

With older versions of Python, there is one macOS quirk that you need to be aware of: programs that talk to the Aqua window manager (in other words, anything that has a GUI) need to be run in a special way. Use pythonw instead of python to start such scripts.

With Python 3.9, you can use either python or pythonw.

5.1.3. ConfigurationВ¶

Python on macOS honors all standard Unix environment variables such as PYTHONPATH , but setting these variables for programs started from the Finder is non-standard as the Finder does not read your .profile or .cshrc at startup. You need to create a file

/.MacOSX/environment.plist . See Apple’s Technical Document QA1067 for details.

For more information on installation Python packages in MacPython, see section Installing Additional Python Packages .

5.2. The IDEВ¶

MacPython ships with the standard IDLE development environment. A good introduction to using IDLE can be found at http://www.hashcollision.org/hkn/python/idle_intro/index.html.

5.3. Installing Additional Python PackagesВ¶

There are several methods to install additional Python packages:

Packages can be installed via the standard Python distutils mode ( python setup.py install ).

Читайте также:  При включении ноутбука гибернация windows 10

Many packages can also be installed via the setuptools extension or pip wrapper, see https://pip.pypa.io/.

5.4. GUI Programming on the MacВ¶

There are several options for building GUI applications on the Mac with Python.

PyObjC is a Python binding to Apple’s Objective-C/Cocoa framework, which is the foundation of most modern Mac development. Information on PyObjC is available from https://pypi.org/project/pyobjc/.

The standard Python GUI toolkit is tkinter , based on the cross-platform Tk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is bundled with OS X by Apple, and the latest version can be downloaded and installed from https://www.activestate.com; it can also be built from source.

wxPython is another popular cross-platform GUI toolkit that runs natively on macOS. Packages and documentation are available from https://www.wxpython.org.

PyQt is another popular cross-platform GUI toolkit that runs natively on macOS. More information can be found at https://riverbankcomputing.com/software/pyqt/intro.

5.5. Distributing Python Applications on the MacВ¶

The standard tool for deploying standalone Python applications on the Mac is py2app. More information on installing and using py2app can be found at http://undefined.org/python/#py2app.

5.6. Other ResourcesВ¶

The MacPython mailing list is an excellent support resource for Python users and developers on the Mac:

Another useful resource is the MacPython wiki:

Источник

What should be my python packages path for a user install on MacOS?

I’m on Mac OS X and I’ve heard that to avoid global installation of packages (using sudo) that might cause problems with the python files that OS X uses, the path to install python packages must be different than that of OS X.

Currently python executables are installed in :

Pip installs modules over here :

Python is used from here :

Are these paths safe?

4 Answers 4

If you are on OS X, you should also have Python in /usr/bin :

If you are using brew , the first python should be a symlink:

If you are not using brew , you will have to explain to us how you installed a second version of python .

You should also have at least two site-packages :

If you installed python using brew , you should also have pip :

You should probably upgrade that to the latest pip :

It should be safe to install python packages using /usr/local/bin/pip because they will be installed in /usr/local/lib/python2.7/site-packages . The /usr/local path is specifically for local software. Also, brew installs its files to /usr/local , so if you are using brew , you are already installing files there.

I am not sure why some folks say not to install any packages globally. I have never seen a reference that explained why this was a bad idea. If multiple users need the same package, it makes more sense to install it globally.

When I first started using virtualenv , it did not always work the way I expected it to. I had a machine with multiple users that needed requests , and because of problems with virtualenv , I wound up installing it globally using pip .

Both virtualenv and pip have improved a lot since I first started using them and I can see how using them can prevent some problems. If you are developing new software that needs the latest version of a package, virtualenv allows you to install the package without affecting the rest of the system. However, I still do not see why it is a bad idea to install packages globally.

Источник

Installing Packages¶

This section covers the basics of how to install Python packages .

It’s important to note that the term “package” in this context is being used to describe a bundle of software to be installed (i.e. as a synonym for a distribution ). It does not to refer to the kind of package that you import in your Python source code (i.e. a container of modules). It is common in the Python community to refer to a distribution using the term “package”. Using the term “distribution” is often not preferred, because it can easily be confused with a Linux distribution, or another larger software distribution like Python itself.

Requirements for Installing Packages¶

This section describes the steps to follow before installing other Python packages.

Ensure you can run Python from the command line¶

Before you go any further, make sure you have Python and that the expected version is available from your command line. You can check this by running:

You should get some output like Python 3.6.3 . If you do not have Python, please install the latest 3.x version from python.org or refer to the Installing Python section of the Hitchhiker’s Guide to Python.

If you’re a newcomer and you get an error like this:

It’s because this command and other suggested commands in this tutorial are intended to be run in a shell (also called a terminal or console). See the Python for Beginners getting started tutorial for an introduction to using your operating system’s shell and interacting with Python.

If you’re using an enhanced shell like IPython or the Jupyter notebook, you can run system commands like those in this tutorial by prefacing them with a ! character:

Читайте также:  Экран блокировки windows 10 не работает слайд шоу

It’s recommended to write rather than plain python in order to ensure that commands are run in the Python installation matching the currently running notebook (which may not be the same Python installation that the python command refers to).

Due to the way most Linux distributions are handling the Python 3 migration, Linux users using the system Python without creating a virtual environment first should replace the python command in this tutorial with python3 and the python -m pip command with python3 -m pip —user . Do not run any of the commands in this tutorial with sudo : if you get a permissions error, come back to the section on creating virtual environments, set one up, and then continue with the tutorial as written.

Ensure you can run pip from the command line¶

Additionally, you’ll need to make sure you have pip available. You can check this by running:

If you installed Python from source, with an installer from python.org, or via Homebrew you should already have pip. If you’re on Linux and installed using your OS package manager, you may have to install pip separately, see Installing pip/setuptools/wheel with Linux Package Managers .

If pip isn’t already installed, then first try to bootstrap it from the standard library:

If that still doesn’t allow you to run python -m pip :

Run python get-pip.py . 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.

Be cautious if you’re using a Python install that’s managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state. You can use python get-pip.py —prefix=/usr/local/ to install in /usr/local which is designed for locally-installed software.

Ensure pip, setuptools, and wheel are up to date¶

While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:

Optionally, create a virtual environment¶

See section below for details, but here’s the basic venv 3 command to use on a typical Linux system:

This will create a new virtual environment in the tutorial_env subdirectory, and configure the current shell to use it as the default python environment.

Creating Virtual Environments¶

Python “Virtual Environments” allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally. If you are looking to safely install global command line tools, see Installing stand alone command line tools .

Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python3.6/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtual environments can help you. They have their own installation directories and they don’t share libraries with other virtual environments.

Currently, there are two common tools for creating Python virtual environments:

venv is available by default in Python 3.3 and later, and installs pip and setuptools into created virtual environments in Python 3.4 and later.

virtualenv needs to be installed separately, but supports Python 2.7+ and Python 3.3+, and pip , setuptools and wheel are always installed into created virtual environments by default (regardless of Python version).

Источник

Как найти расположение моего каталога Python site-packages?

Как найти расположение каталога мой сайт-пакеты?

17 ответов:

существует два типа каталогов site-packages,глобальные и для каждого пользователя.

глобальные site-packages (» dist-packages») каталоги перечислены в sys.path при запуске:

для более краткого списка выполнить getsitepackages С модуль сайта в коде Python:

Примечание: С virtualenvs getsitepackages is недоступно, sys.path сверху будет правильно указан каталог site-packages virtualenv.

The для каждого пользователя каталог site-packages (PEP 370) где Python устанавливает ваши локальные пакеты:

если это указывает на несуществующий каталог, проверьте состояние выхода Python и см. python -m site —help для объяснения.

подсказка: под управлением pip list —user или pip freeze —user дает вам список всех установленных для каждого пользователя сайт-пакеты.

(или просто первый пункт с site.getsitepackages()[0] )

С » Как установить Django » документация (хотя это полезно не только для установки Django) — выполните следующее из оболочки:

отформатирован для удобства чтения (а не использовать в качестве подводки), которая выглядит следующим образом:

Читайте также:  Пропала кнопка windows интересное

Он будет указывать вам!—1—>

эта папка содержит только пакеты, которые ваша операционная система автоматически установила для запуска программ.

на ubuntu, папка site-packages, содержащая пакеты, установленные через setup_tools\easy_install\pip, будет находиться в /usr/local/lib/pythonX.X/dist-packages

вторая папка, вероятно, более полезна, если случай использования связано с установкой или чтением исходного кода.

Если вы не используете Ubuntu, вы, вероятно, безопасно копируете первое поле кода в терминал.

Это то, что сработало для меня:

как уже отмечалось, distutils.sysconfig имеет соответствующие параметры:

. хотя по умолчанию site.py делает что-то немного более сырой, перефразировал ниже:

(он также добавляет $/lib/site-python и добавляет оба пути для sys.exec_prefix а также, если эта константа будет отличаться).

что сказал, каков контекст? Вы не должны возиться с вашим site-packages напрямую; setuptools/distutils будет работать для установки, и ваша программа может быть запущена в virtualenv, где ваш pythonpath полностью является локальным пользователем,поэтому он не должен предполагать использование системных пакетов сайта напрямую.

допустим, вы установили пакет ‘django’. импортируйте его и введите в dir(django). Он покажет вам все функции и атрибуты с этим модулем. Введите интерпретатор python —

вы можете сделать то же самое, если вы установили mercurial.

Это для снежного барса. Но я думаю, что это должно работать в целом.

собственные системные пакеты, установленные с установкой python в системах на основе Debian, можно найти по адресу :

в OSX — /Library/Python/2.7/site-packages

С помощью этого небольшого кода:

тем не менее, список пакетов, установленных через pip можно найти в :

или можно просто написать следующую команду, чтобы перечислить все пути где находятся пакеты python.

Примечание: расположение может отличаться в зависимости от вашей ОС, как в OSX

все ответы (или: один и тот же ответ повторяется снова и снова) неадекватны. Что вы хотите сделать это:

в последней строке отображается установочный каталог. Не спрашивайте меня о windows или других дисках, но поскольку это тот же самый dir, который использует easy_install по умолчанию, это, вероятно, правильно везде, где работает easy_install (так, везде, даже Mac). Повеселись. Примечание: оригинальный код имеет много ругательств в оно.

боковое Примечание: предлагаемое решение ( distutils.sysconfig.get_python_lib() ) не работает, когда есть несколько каталогов site-packages (как рекомендовано в статье). Он будет возвращать только основной каталог site-packages.

увы, у меня нет лучшего решения. Python, похоже, не отслеживает каталоги site-packages, а только пакеты внутри них.

это работает для меня. Он получит вам как папки dist-packages, так и site-packages. Если папка не находится на пути Python, она не будет в любом случае, тебе это очень полезно.

выход (установка Ubuntu):

дополнительно к get_python_lib функция уже упоминалось: на некоторых платформах различные каталоги используются для конкретных модулей платформы (например: модули, которые требуют компиляции). Если вы пройдете plat_specific=True в функцию вы получаете пакеты сайта для конкретных пакетов платформы.

Это должно работать на всех дистрибутивах В и из виртуальной среды из-за его» низкотехнологичной » природы. Модуль ОС всегда находится в Родительском каталоге ‘site-packages’

чтобы изменить dir на сайт-пакеты dir я использую следующий псевдоним (на *Nix системах):

ответ на старый вопрос. Но для этого используйте ipython.

это даст следующий вывод о пакете imaplib —

современный способ stdlib использует sysconfig модуль, доступный в версии 2.7 и 3.2+. Python в настоящее время использует восемь дорожки (docs):

  • stdlib: каталог, содержащий стандартные файлы библиотеки Python, которые не зависят от платформы.
  • platstdlib: каталог, содержащий стандартные файлы библиотеки Python, которые зависят от платформы.
  • platlib: каталог для специфичных для сайта и платформы файлов.
  • purelib: каталог для специфичных для сайта, не связанных с платформой файлов.
  • включить: каталог для файлов заголовков, не зависящих от платформы.
  • platinclude: каталог для специфичных для платформы заголовочных файлов.
  • скрипты каталог файлов скрипт.
  • сведения каталог файлов данных.

в большинстве случаев пользователи, обнаруживающие этот вопрос, будут заинтересованы в пути «purelib» (in в некоторых случаях, вы можете быть заинтересованы в ‘platlib’ тоже). В отличие от принятого в настоящее время ответа, этот метод не должен плохо себя вести в зависимости от того, активирован ли virtualenv.

на системном уровне (это Python 3.7.0 на mac OS):

С a венв, ты получишь что-то вроде этого

сценарий оболочки также доступен для отображения этих сведений, которые можно вызвать, выполнив sysconfig как модуль:

Примечание: sysconfig (источник) не следует путать с distutils.sysconfig подмодуля (источник) упоминается в нескольких других ответах здесь. Это совершенно другой модуль, и ему не хватает

Я должен был сделать что-то немного другое для проекта, над которым я работал: найти относительные каталог site-packages относительно базового префикса установки. Если папка site-packages была в /usr/lib/python2.7/site-packages , Я хочу /lib/python2.7/site-packages часть. Я, по сути, столкнулся с системами, где site-packages был в /usr/lib64 , и принятый ответ не работал на этих системах.

подобно ответу мошенника, мое решение заглядывает глубоко в кишки Distutils, чтобы найти путь, который на самом деле передается внутри setup.py . Это была такая боль, чтобы понять, что я не хочу, чтобы кто-нибудь когда-нибудь думать с этим.

это должно печатать что-то вроде /Lib/site-packages или /lib/python3.6/site-packages .

Источник

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