IDLE and tkinter with Tcl/Tk on macOS
If you are using macOS 12 Monterey or later, you may see problems with file open and save dialogs when using IDLE or other tkinter-based applications. The most recent versions of python.org installers (for 3.10.0 and 3.9.8) have patched versions of Tk to avoid these problems. They should be fixed in an upcoming Tk 8.6.12 release.
If you are using a Python from any current python.org Python installer for macOS (3.10.0+ or 3.9.0+), no further action is needed to use IDLE or tkinter. A built-in version of Tcl/Tk 8.6 will be used.
If you are using macOS 10.6 or later, the Apple-supplied Tcl/Tk 8.5 has serious bugs that can cause application crashes. If you wish to use IDLE or Tkinter, do not use the Apple-supplied Pythons. Instead, install and use a newer version of Python from python.org or a third-party distributor that supplies or links with a newer version of Tcl/Tk.
Python’s integrated development environment, IDLE, and the tkinter GUI toolkit it uses, depend on the Tk GUI toolkit which is not part of Python itself. For best results, it is important that the proper release of Tcl/Tk is installed on your machine. For recent Python installers for macOS downloadable from this website, here is a summary of current recommendations followed by more detailed information.
| Python Release | Installer Variant | macOS Release | Recommended Tcl/Tk | Alternate Tcl/Tk | Not Recommended |
|---|---|---|---|---|---|
| 3.10.0, 3.9.8 | universal2 | 10.9+ | built-in 8.6.11 | ||
| 3.9.8 | Intel-only | 10.9+ | built-in 8.6.8 |
Tk On macOS
There are currently three major variants of Tk in common use on macOS:
Aqua Cocoa Tk A newer native implementation available as a universal 64-bit and 32-bit binary. This variant is the standard native macOS variant in Tk 8.6 and as of Tk 8.5.13. Aqua Cocoa support was backported to Tk 8.5 (prior to 8.5.13) and released by Apple starting with macOS 10.6 and by ActiveState starting with their 8.5.9.1 release. Aqua Carbon Tk Because it is implemented with older macOS Carbon interfaces, it is only available as a 32-bit binary (usually for Intel and PowerPC processors). Aqua Carbon Tk 8.4 is included with macOS releases 10.4 through 10.14 and is also available from ActiveState. Aqua Carbon variants of Tk 8.5 had been available as an ActiveState Community Download prior to ActiveTcl 8.5.9. As of 8.5.13, the Tk project no longer supports Carbon builds of Tk 8.5. 32-bit-only Python installers downloadable from this website for older Python releases were linked with Aqua Carbon Tk 8.4. X11 Tk The traditional platform-independent UNIX Tk implementation which requires an X11 server, such as the Apple X11.app available as an optional component in older macOS releases or from third-party distributors. 64-bit and 32-bit binaries can be built. While the Python installers downloadable from this website do not support X11 Tk, other distributors of Python for macOS may do so.
Tcl/Tk Releases
built-in 8.6.11
As of Python 3.9.1, all current universal2 Python installers for macOS downloadable from python.org supply their own private copies of Tcl/Tk 8.6.11. They do not look for or use any third-party or system copies of Tcl/Tk. This is an Aqua Cocoa Tk.
built-in 8.6.8
As of Python 3.7.0, 3.6.8, and 2.7.16, all current legacy 64-bit Intel-only Python installers for macOS downloadable from python.org supply their own private copies of Tcl/Tk 8.6.8. They do not look for or use any third-party or system copies of Tcl/Tk. This is an Aqua Cocoa Tk.
ActiveTcl 8.5.18.0
ActiveState provides binary distributions of Tcl/Tk which are upward compatible with and generally more up-to-date than those provided by Apple in macOS releases. This version of Tcl/Tk includes fixes for some critical problems that you may encounter using tkinter or IDLE (see Apple 8.5.9 below). You can download an installer for this release from the ActiveState web site. Note that ActiveState Community Edition binaries are not open source and are covered by an ActiveState license. You should read the license before downloading to verify that your usage complies with its terms of use. As of Python 3.7.0, 3.6.8, and 2.7.16, no current Python installers for macOS downloadable from python.org make use of this or any other external version of Tcl/Tk.
This is an Aqua Cocoa Tk.
Apple 8.5.9
This release is included in macOS 10.7 through at least macOS 10.14. As of this writing, there are at least two known issues with Tk 8.5.9 that are present in Apple 8.5.9 Tk but fixed in more recent upstream 8.5 releases. The more serious problem is an immediate crash in Tk when entering a composition character, like Option-u on a US keyboard. (This problem is documented as Tk bug 2907388.) There is also the more general problem of input manager support for composite characters (Tk bug 3205153) which has also been fixed in more recent Tcl/Tk 8.5 releases. You can avoid these problems by using a current python.org installer or by using a third-party distribution of Python that does not use Apple 8.5.9 Tk. This is an Aqua Cocoa Tk.
Apple 8.5.7
This release is included in macOS 10.6. IDLE is known to hang or crash when used with the Apple 8.5.7 included in all versions of macOS 10.6.x. Because of this, we strongly recommend that you do not attempt to use Tkinter or IDLE with the Apple-supplied Python 2.6.1 in 10.6. Instead, install a newer version of Python that supports a newer version of Tk. This is an Aqua Cocoa Tk.
How Python Chooses Which Tk Library To Use
While Tcl and Tk are separate frameworks and libraries, they are closely related and are normally installed or updated simultaneously. You should not attempt to mix-and-match Tcl and Tk versions. References to a specific version of Tk assume the corresponding version of Tcl is installed as well.
The Python for macOS installers downloaded from this website dynamically link at runtime to Tcl/Tk macOS frameworks. The Tcl/Tk major version is determined when the installer is created and cannot be overridden. All current python.org installers link to their own built-in Tcl/Tk 8.6 frameworks and do not use external Tcl/Tk frameworks so the rest of this section only applies to non-current releases and, as such, no longer supported.
The Python 64-bit/32-bit macOS installers for Python 3.6.x and and 2.7.x dynamically link to Tcl/Tk 8.5 frameworks. The dynamically linking occurs when tkinter (Python 3) or Tkinter (Python 2) is first imported (specifically, the internal _tkinter C extension module). By default, the macOS dynamic linker looks first in /Library/Frameworks for Tcl and Tk frameworks with the proper major version. This is the standard location for third-party or built from source frameworks, including the ActiveTcl releases. If frameworks of the proper major version are not found there, the dynamic linker looks for the same version in /System/Library/Frameworks, the location for Apple-supplied frameworks shipped with macOS. (Note, you should normally not modify or delete files in /System/Library.)
As is common on macOS, the installed Pythons and the Tcl and Tk frameworks are built to run on multiple CPU architectures (universal binaries) and across multiple macOS levels (minimum deployment target). For Python to be able to dynamically link with a particular Tcl and Tk version, the available architectures in the Tcl/Tk frameworks must include the architecture that Python is running in and their minimum deployment target should be no greater than that of Python.
Revision history
- 2021-11-05 — updated for 3.9.8 and macOS 12 Monterey
- 2021-10-04 — updated for 3.10.0 and 3.9.7
- 2020-10-05 — updated for 3.9.0 and 3.8.6, remove 2.7
- 2020-08-17 — updated for 3.7.9
- 2020-07-20 — updated for 3.8.5
- 2020-06-27 — updated for 3.7.8
- 2020-05-14 — updated for 3.8.3
- 2020-03-10 — updated for 3.8.2 and 3.7.7
- 2019-12-19 — updated for 3.8.1, 3.7.6, and 2.7.17
- 2019-10-15 — updated for 3.8.0, 3.7.5, and macOS 10.15
- 2019-07-08 — updated for 3.7.4; 3.6.x is now security-fix-only
- 2019-03-25 — updated for 3.7.3
- 2019-03-03 — updated for 2.7.16
- 2018-12-24 — updated for 3.7.2 and 3.6.8
- 2018-10-20 — updated for 3.7.1, 3.6.7, and macOS 10.14
- 2018-06-27 — updated for 3.7.0 and 3.6.6
- 2018-05-30 — updated for 3.7.0b5
- 2018-05-02 — updated for 3.7.0b4 and 2.7.15; removed 32-bit-only refs
- 2018-03-29 — updated for 3.7.0b3 and 3.6.5
- 2018-02-28 — updated for 3.7.0b2
- 2018-01-31 — updated for 3.7.0b1 and 3.6.4
- 2017-10-03 — updated for 3.6.3 and macOS 10.13
- 2017-09-16 — updated for 2.7.14; removed 3.5.x
- 2017-07-17 — updated for 3.6.2
- 2017-03-21 — updated for 3.6.1 and (belatedly) 3.5.3
- 2016-12-23 — updated for 3.6.0
- 2016-12-17 — updated for 2.7.13
- 2016-09-23 — updated for macOS 10.12
- 2016-07-31 — updated for 3.5.2 and 2.7.12; removed 3.4.x
- 2015-12-20 — updated for 3.4.4
- 2015-12-06 — updated for 3.5.1, 2.7.11, and macOS 10.11
- 2015-09-13 — updated for 3.5.0
- 2015-05-23 — updated for 2.7.10 and ActiveTcl 8.5.18.0
- 2015-02-23 — updated for 3.4.3
- 2014-12-10 — updated for 2.7.9 and ActiveTcl 8.5.17.0
- 2014-10-16 — updated for macOS 10.10
- 2014-10-06 — updated for 3.4.2 and ActiveTcl 8.5.16.0
- 2014-09-22 — updated for 3.4.2rc1
- 2014-07-01 — updated for 2.7.8
- 2014-06-01 — updated for 2.7.7; removed 2.7.6 and 3.3.5
- 2014-05-18 — updated for 3.4.1 and 2.7.7rc1
- 2014-03-16 — updated for 3.4.0 and 3.3.5
- 2014-02-10 — updated for 3.3.4 and 3.4.0rc1
- 2014-01-05 — updated for 3.4.0b2
- 2013-11-24 — clarify that the ActiveState website still refers to 8.5.15.0
- 2013-11-24 — removed built-in for 3.4.0b1, removed 3.3.2 and 2.7.5
- 2013-11-10 — ActiveTcl 8.5.15.1; removed built-in for 3.3.3rc2 and 2.7.6.
- 2013-10-27 — updated for 3.3.3rc1 and 2.7.6rc1 and their built-in 8.5.15.
- 2013-10-24 — updated for macOS 10.9 and ActiveTcl 8.5.15, removed 3.2.5.
- 2013-10-20 — updated for 3.4.0a4 and its built-in 8.5.15.
- 2013-09-29 — updated for 3.4.0a3
- 2013-09-09 — updated for 3.4.0a2 and its built-in 8.5.14.
- 2013-08-03 — updated for 3.4.0a1 and ActiveTcl 8.4.20
- 2013-05-18 — updated for ActiveTcl 8.5.14
- 2013-05-15 — updated for 3.3.2, 2.7.5, and 3.2.5
- 2013-04-06 — updated for 3.3.1, 2.7.4, and 3.2.4
- 2012-12-26 — updated for ActiveTcl 8.5.13 and Issue 15853 patch installer
- 2012-09-29 — updated for 3.3.0 final and reverted to ActiveTcl 8.5.11.1
- 2012-08-02 — updated for ActiveTcl 8.5.12
- 2012-07-28 — updated for macOS 10.8
- 2012-04-11 — updated for 3.2.3 final and 2.7.3 final
- 2012-03-18 — updated for 3.2.3rc2 and 2.7.3rc2
- 2012-03-04 — updated for ActiveTcl 8.5.11.1, 3.2.3rc1, 2.7.3rc1, removed 3.1.4
- 2011-11-12 — updated for ActiveTcl 8.5.11
- 2011-09-04 — updated for 3.2.2 final
- 2011-07-21 — updated for macOS 10.7 and ActiveTcl 8.5.10.1
- 2011-07-09 — updated for 3.2.1 final and ActiveTcl 8.5.10
- 2011-06-12 — updated for 2.7.2 final and 3.1.4 final
- 2011-05-30 — updated for 3.2.1rc, 2.7.2rc, and 3.1.4rc
- 2011-03-08 — add warnings and include details on how Python links with Tcl/Tk releases
- 2011-02-20 — updated for 3.2 final
- 2011-01-31 draft 1 — preliminary info for 3.2rc2
- 2011-01-14 draft 0
The PSF
The Python Software Foundation is the organization behind Python. Become a member of the PSF and help advance the software and our mission.
- About
- Applications
- Quotes
- Getting Started
- Help
- Python Brochure
- All releases
- Source code
- Windows
- macOS
- Other Platforms
- License
- Alternative Implementations
- Docs
- Audio/Visual Talks
- Beginner’s Guide
- Developer’s Guide
- FAQ
- Non-English Docs
- PEP Index
- Python Books
- Python Essays
- Diversity
- Mailing Lists
- IRC
- Forums
- PSF Annual Impact Report
- Python Conferences
- Special Interest Groups
- Python Logo
- Python Wiki
- Code of Conduct
- Community Awards
- Get Involved
- Shared Stories
- Arts
- Business
- Education
- Engineering
- Government
- Scientific
- Software Development
- Python News
- PSF Newsletter
- PSF News
- PyCon US News
- News from the Community
- Python Events
- User Group Events
- Python Events Archive
- User Group Events Archive
- Submit an Event
- Developer’s Guide
- Issue Tracker
- python-dev list
- Core Mentorship
- Report a Security Issue
- Help & General Contact
- Diversity Initiatives
- Submit Website Bug
- Status
Pyenv and Pipenv (on MacOS)
This tutorial describes the different options to install, uninstall, configure, and use various versions of Python with its various packages, all running in a virtual environment also managed by pyenv.
NOTE: Content here are my personal opinions, and not intended to represent any employer (past or present). “PROTIP:” here highlight information I haven’t seen elsewhere on the internet because it is hard-won, little-know but significant facts based on my personal research and experience.
Why pipenv?
The value of pyenv is:
- Install Python in your user space (without need for sudo)
- Install multiple parallel versions of Python
- Dynamically specify the exact Python version you want
- Switch between installed versions without resetting your bash session
What is the magic of pyenv?
In this article I take a carefully crafted narrated tour. Here is a hands-on “deep dive” tutorial so you better grasp the complexities in a shorter time. Why? Because I haven’t seen one on the internet.
pyenv uses a technique called “rehashing” so it can switch among multiple versions of Python2 or Python3.
Commands for the operating system to execute “python3” are intercepted by a shim executable which passes commands along to the actual Python installation of the desired version.
That’s achieved by a line at the bottom of your ~/.bash_profile which makes the operating system search in the shims folder for programs:
export PATH="$PYENV_ROOT/shims:$PATH"
This technique is possible because the operating system searches for executables in folders in the PATH from left to right.
Thus, which aws would return:
/Users/wilson_mar/.pyenv/shims/aws
Competitors
The alternative to Pyenv is Conda and MiniConda.
What are installed?
PROTIP: Before installing things, first see what is already installed.
-
Get a list of the various locations where Python is installed (by various installers):
type -a python
A new macOS version would show:
python is /usr/bin/python
PROTIP: The /usr/bin/ folder is owned by the operating system, so elevated sudo priviledges are required to modify files in it (such as “python”). So Homebrew and other installers install to the User-owned /usr/local/ which does NOT require sudo to access. Different installers install Python in different paths (but instead of “wilson_mar”, you’ll see your own user name):
python is /Users/wilson_mar/.pyenv/shims/python python is /Users/wilson_mar/anaconda3/bin/python python3 is /usr/local/opt/python@3.8/bin/python3 python is /usr/local/anaconda3/bin/python python is /usr/bin/python
You are good to go with Pipenv if you see in the first response to the type -a python command (but instead of “wilson_mar”, you’ll see your own user name):
python3 is /Users/wilson_mar/.pyenv/shims/python3
/usr/local/opt/python@3.8/bin/python3
which python
The response is
/usr/bin/python
because the file “python” in actually a symbolic link to the actual executable.
System Python2
ls -l /usr/bin/python
lrwxr-xr-x 1 root wheel 75 Apr 15 03:55 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
ls /System/Library/Frameworks/Python.framework/Versions/2.7/bin/
Listed are executables “python”, “python2”, and “python2.7”, plus others.
View $PATH
echo $PATH
If that’s too much, view it in a file by a text editor:
echo "$PATH" >path.txt edit path.txt rm path.txt
python2 --version
On a MacOS Catalina version operating system, you would see:
Python 2.7.16
python2 -V
python -V
The response would be:
Python 3.7.8
Ways to Install Python3
Before pyenv, people define what version of “python” is executed by editing the PATH variable – putting the path to Python3 executables before Python2 in $PATH. To have Python3 execute instead of Python2:
export PATH="/usr/local/python3:$PATH"
(Colon characters separate folders in the PATH) Alternately, Azure recommends this line at the bottom of ~/.bash_profile files:
export PATH="/usr/local/opt/python@3.8/bin:$PATH"
The line above overrides the system’s type command described above.
Don’t alias with pyenv
Some add aliases within the ~/.bash_profile or ~/.zshenv file:
alias python=python3 alias pip=pip3
But don’t do that when you’re using pyenv, which makes use of shims. NOTE: pyenv is for macOS.
Windows install
Ubuntu install
Brew Install Pyenv on Mac
brew install pyenv
The response at time of this writing:
==> Installing dependencies for pyenv: openssl@1.1 and pkg-config ==> Installing pyenv dependency: openssl@1.1 ==> Downloading https://homebrew.bintray.com/bottles/openssl@1.1-1.1.1g.catalina ==> Downloading from https://akamai.bintray.com/19/1926679569c6af5337de812d86f4d ==> Pouring openssl@1.1-1.1.1g.catalina.bottle.tar.gz ==> Caveats A CA file has been bootstrapped using certificates from the system keychain. To add additional certificates, place .pem files in /usr/local/etc/openssl@1.1/certs and run /usr/local/opt/openssl@1.1/bin/c_rehash openssl@1.1 is keg-only, which means it was not symlinked into /usr/local, because macOS provides LibreSSL. If you need to have openssl@1.1 first in your PATH run: echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.bash_profile For compilers to find openssl@1.1 you may need to set: export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib" export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include" For pkg-config to find openssl@1.1 you may need to set: export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig" ==> Summary /usr/local/Cellar/openssl@1.1/1.1.1g: 8,059 files, 18MB ==> Installing pyenv dependency: pkg-config ==> Downloading https://homebrew.bintray.com/bottles/pkg-config-0.29.2_3.catalin ==> Downloading from https://akamai.bintray.com/80/80f141e695f73bd058fd82e9f539d ==> Pouring pkg-config-0.29.2_3.catalina.bottle.tar.gz Error: The `brew link` step did not complete successfully The formula built, but is not symlinked into /usr/local Could not symlink bin/pkg-config Target /usr/local/bin/pkg-config already exists. You may want to remove it: rm '/usr/local/bin/pkg-config' To force the link and overwrite all conflicting files: brew link --overwrite pkg-config To list all files that would be deleted: brew link --overwrite --dry-run pkg-config Possible conflicting files are: /usr/local/bin/pkg-config /usr/local/share/aclocal/pkg.m4 /usr/local/share/doc/pkg-config/pkg-config-guide.html /usr/local/share/man/man1/pkg-config.1 ==> Summary /usr/local/Cellar/pkg-config/0.29.2_3: 11 files, 623.7KB ==> Installing pyenv ==> Downloading https://homebrew.bintray.com/bottles/pyenv-1.2.18.catalina.bottl ==> Downloading from https://akamai.bintray.com/bd/bd9f719f153e9574dcc65dc7fea28 ==> Pouring pyenv-1.2.18.catalina.bottle.tar.gz /usr/local/Cellar/pyenv/1.2.18: 695 files, 2.5MB ==> Caveats ==> openssl@1.1 A CA file has been bootstrapped using certificates from the system keychain. To add additional certificates, place .pem files in /usr/local/etc/openssl@1.1/certs and run /usr/local/opt/openssl@1.1/bin/c_rehash openssl@1.1 is keg-only, which means it was not symlinked into /usr/local, because macOS provides LibreSSL. If you need to have openssl@1.1 first in your PATH run: echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.bash_profile For compilers to find openssl@1.1 you may need to set: export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib" export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include" For pkg-config to find openssl@1.1 you may need to set: export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"
- https://realpython.com/intro-to-pyenv/ about Pyenv Build Dependencies.
- https://github.com/pyenv/pyenv/wiki
- https://github.com/pyenv/pyenv#basic-github-checkout
Verify Install
pyenv --version
At time of writing, the response was the version.release.path semantic version:
pyenv 1.2.26
which pyenv
The response:
/usr/local/bin/pyenv
head -3 /usr/local/bin/pyenv
brew info pyenv
The response, at time of writing, several months after the initial install:
pyenv: stable 1.2.26 (bottled), HEAD Python version management https://github.com/pyenv/pyenv /usr/local/Cellar/pyenv/1.2.26 (747 files, 2.6MB) * Poured from bottle on 2021-04-06 at 10:17:17 From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/pyenv.rb License: MIT ==> Dependencies Required: autoconf ✔, openssl@1.1 ✔, pkg-config ✔, readline ✔ ==> Options --HEAD Install HEAD version
Previously in 1.2.19:
install: 61,768 (30 days), 168,980 (90 days), 637,536 (365 days) install-on-request: 58,851 (30 days), 160,831 (90 days), 594,089 (365 days) build-error: 0 (30 days)
ls -al /usr/local/bin/pyenv
The response shows a link to where Homebrew stores its executable:
lrwxr-xr-x 1 wilson_mar admin 32 Apr 6 10:17 /usr/local/bin/pyenv -> ../Cellar/pyenv/1.2.26/bin/pyenv
PROTIP: The “..” means “/usr/local/” should be added to make the full path: ls -al /usr/local/Cellar/pyenv/1.2.26/bin/pyenv
lrwxr-xr-x 1 wilson_mar staff 16 Apr 5 05:27 /usr/local/Cellar/pyenv/1.2.26/bin/pyenv -> ../libexec/pyenv
pyenv Commands
pyenv
pyenv 1.2.26 Usage: pyenv <command> [<args>] Some useful pyenv commands are: --version Display the version of pyenv activate Activate virtual environment commands List all available pyenv commands deactivate Deactivate virtual environment exec Run an executable with the selected Python version global Set or show the global Python version(s) help Display help for a command hooks List hook scripts for a given pyenv command init Configure the shell environment for pyenv install Install a Python version using python-build local Set or show the local application-specific Python version(s) prefix Display prefix for a Python version rehash Rehash pyenv shims (run this after installing executables) root Display the root directory where versions and shims are kept shell Set or show the shell-specific Python version shims List existing pyenv shims uninstall Uninstall a specific Python version version Show the current Python version(s) and its origin version-file Detect the file that sets the current pyenv version version-name Show the current Python version version-origin Explain how the current Python version is set versions List all Python versions available to pyenv virtualenv Create a Python virtualenv using the pyenv-virtualenv plugin virtualenv-delete Uninstall a specific Python virtualenv virtualenv-init Configure the shell environment for pyenv-virtualenv virtualenv-prefix Display real_prefix for a Python virtualenv version virtualenvs List all Python virtualenvs found in `$PYENV_ROOT/versions/*'. whence List all Python versions that contain the given executable which Display the full path to an executable See `pyenv help ' for information on a specific command. For full documentation, see: https://github.com/pyenv/pyenv#readme
- For a full list of sub-commands recognized by pyenv:
pyenv commands
At time of writing:
--version commands completions exec global help hooks init install local prefix realpath.dylib rehash root shell shims uninstall version version-file version-file-read version-file-write version-name version-origin versions whence which
Where are pyenv shims installed?
ls $( pyenv root )
The response shows that the installer created a folder at my user $HOME folder (but your user name instead of my “wilson_mar”):
plugins shims version versions
ls $(pyenv root)/shims
For example:
2to3 nltk python 2to3-3.7 pathy python-config 2to3-3.8 pbr python3 __pycache__ pdf2txt.py python3-config bandit pdfplumber python3.7 bandit-baseline pip python3.7-config bandit-config-generator pip3 python3.7-gdb.py chardetect pip3.7 python3.7m distro pip3.8 python3.7m-config dumppdf.py pipenv python3.8 easy_install pipenv-resolver python3.8-config easy_install-3.7 pkginfo python3.8-gdb.py easy_install-3.8 pydoc pyuic6 estimator_ckpt_converter pydoc3 pyvenv f2py pydoc3.7 pyvenv-3.7 f2py3 pydoc3.8 saved_model_cli f2py3.7 pyfiglet spacy get_objgraph pyi-archive_viewer spark google-oauthlib-tool pyi-bindepend tabulate idle pyi-grab_version tensorboard idle3 pyi-makespec tf_upgrade_v2 idle3.7 pyi-set_version tflite_convert idle3.8 pyinstaller toco isort pylupdate6 toco_from_protos jake pyrsa-decrypt tqdm latin2ascii.py pyrsa-encrypt undill macho_dump pyrsa-keygen virtualenv macho_find pyrsa-priv2pub virtualenv-clone macho_standalone pyrsa-sign wheel markdown_py pyrsa-verify
find ~/.pyenv/shims -type f | wc -l
How is Pyenv enabled?
# Set it so ~/.pyenv provides Python before others of the same name: export PYENV_ROOT=$(pyenv root) export PATH="$PYENV_ROOT/shims:$PATH"
Put the above at the bottom of the file. Alternately, if you don’t want to mess with a text editor, use this command:
echo 'export PATH="$(pyenv root)/bin:$PATH"' >> ~/.bash_profile
Instead of .bash_profile, specify ~/.zshrc or ~/.bashrc (for Ubuntu/Fedora).
$(pyenv root)/shims:/usr/local/bin:/usr/bin:/bin
exec "$SHELL" source ~/.bash_profile
~/.zshrc
echo "$PATH" >path.txt edit path.txt rm path.txt
which python
Response should be:
/Users/wilson_mar/.pyenv/shims/python
(“wilson_mar” would be replaced with your user name)
What Python Releases are available?
Pyenv can install several releases of Python. PROTIP: Each version of Python is installed within pyenv’s versions folder:
ls $( pyenv root)/versions
brew install tree
tree -d -L 1 $( pyenv root )/versions
/Users/wilson_mar/.pyenv/versions ├── 3.7.7 ├── 3.7.9 ├── 3.8.2 └── 3.8.5
pyenv install --list | grep " 3\.[789]"
At time of writing:
3.7.0 3.7-dev 3.7.1 3.7.2 3.7.3 3.7.4 3.7.5 3.7.6 3.7.7 3.7.8 3.7.9 3.7.10 3.8.0 3.8-dev 3.8.1 3.8.2 3.8.3 3.8.4 3.8.5 3.8.6 3.8.7 3.8.8 3.8.9 3.9.0 3.9-dev 3.9.1 3.9.2 3.9.3 3.9.4
PROTIP: Select the last patch number of a release, such as “3.7.7” or “3.8.2” in the example above.
-dev releases are the ones under active development (changes).
Install Python using pyenv
- Navigate to the folder containing your Python .py file.
- To install a specific version of Python (selected from the response above):
pyenv install 3.7.7
python-build: use openssl@1.1 from homebrew python-build: use readline from homebrew Downloading Python-3.7.7.tar.xz. -> https://www.python.org/ftp/python/3.7.7/Python-3.7.7.tar.xz Installing Python-3.7.7. python-build: use readline from homebrew python-build: use zlib from xcode sdk Installed Python-3.7.7 to /Users/wilson_mar/.pyenv/versions/3.7.7
pyenv install 3.8.2
python-build: use openssl@1.1 from homebrew python-build: use readline from homebrew Downloading Python-3.8.2.tar.xz. -> https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tar.xz Installing Python-3.8.2. python-build: use readline from homebrew python-build: use zlib from xcode sdk Installed Python-3.8.2 to /Users/wilson_mar/.pyenv/versions/3.8.2
pyenv versions
In the response such as:
* 3.7.7 (set by /Users/wilson_mar/.python-version) 3.7.9 3.8.2 3.8.5
* indicates the current system Python release.
Set Version of Python using Pyenv
pyenv global 3.7.9
pyenv local 3.7.7
python --version
Order of Path override
- $PYENV_VERSION environment variable
- pyenv local x.y.z
- pyenv global x.y.z
This means the PYENV_VERSION environment variable overrides all other specifications.
pyenv local 2.7.15
pyenv global 3.7.7
Virtual Environments
Both Pipenv and Pipenv automatically creates and manages a virtualenv for your projects. But only Pipenv adds/removes packages from your Pipfile as you install/uninstall packages. Pipenv generates the Pipfile.lock file used to produce deterministic builds.
Pipenv enables always use the latest versions of dependencies, to minimize security risks arising from outdated components.
pyenv copies an entire Python installation every time a new pyenv version is created.
By contrast, virtualenv makes use of symbolic links, which decreases the size of each virtualenv.
There are two utilities to add virtualenv functionality to pyenv: pyenv-virtualenvwrapper (described by https://alysivji.github.io/setting-up-pyenv-virtualenvwrapper.html) is less convenient and has less stars than the pyenv-virtualenv plugin. To install it:
brew install pyenv-virtualenv
git clone https://github.com/pyenv/pyenv-virtualenv.git \ $(pyenv root)/plugins/pyenv-virtualenv source ~/.bashrc
Cloning into '/Users/wilson_mar/.pyenv/plugins/pyenv-virtualenv'. remote: Enumerating objects: 2064, done. remote: Total 2064 (delta 0), reused 0 (delta 0), pack-reused 2064 Receiving objects: 100% (2064/2064), 580.31 KiB | 30.00 KiB/s, done. Resolving deltas: 100% (1413/1413), done.
This is needed because Virtualenv and Anaconda also activate scripts by mutating $PATH variable of user’s interactive shell, which intercepts pyenv’s shim style command execution hooks.
To automatically activate/deactivate virtualenvs on entering/leaving directories which contain a .python-version file that contains the name of a valid virtual environment as shown in the output of pyenv virtualenvs
echo ‘eval “$(pyenv virtualenv-init -)”’ » ~/.bash_profile or ~/.zshrc
-
List what virtualenv has been defined
pyenv virtualenvs
pyenv virtualenvs
Setup Virtual environments
python -m venv venv
No response is returned if it’s all good. The above creates a virtual folder named after the project. To deactivate, type:
exit
Alternately, to activate virtualenv, run:
pipenv shell
Alternatively, run a command inside the virtualenv
pipenv run
source ./venv/bin/activate
/Users/. my_project/venv/bin/python
Pipfile.lock
Upgrade Pyenv
If you see this error:
/Users/. /.pyenv/shims/python3: line 21: /usr/local/Cellar/pyenv/1.2.20/libexec/pyenv: No such file or directory
brew upgrade pyenv
References for pyenv
References for pipenv
- https://stackoverflow.com/questions/58300046/how-to-make-lightweight-docker-image-for-python-app-with-pipenv
- https://github.com/Ilhicas/alpine-pipenv
More about Python
This is one of a series about Python:
- Python install on MacOS
- Python install on MacOS using Pyenv
- Python install on Raspberry Pi for IoT
- Python tutorials
- Python Examples
- Python coding notes
- Pulumi controls cloud using Python, etc.
- Jupyter Notebooks provide commentary to Python
- Python certifications
- Test Python using Pytest BDD Selenium framework
- Test Python using Robot testing framework
- Testing AI uses Python code
- Microsoft Azure Machine Learning makes use of Python
- Python REST API programming using the Flask library
- Python coding for AWS Lambda Serverless programming
- Streamlit visualization framework powered by Python
- Web scraping using Scrapy, powered by Python
- Neo4j graph databases accessed from Python
More on OSX
This is one of a series on Mac OSX:
- MacOS Setup step-by-step, with automation
- MacOS Hardware and accessories
- MacOS dotfiles for System Preferences setup automation
- MacOS Homebrew installers
- MacOS Boot-up
- MacOS Versions
- MacOS Keyboard tricks
- MacOS Terminal Tips and Tricks
- MacOS Find (files and text in files)
- Text editors and IDEs on MacOS
- MacOS Xcode.app and CommandTools (gcc)
- MacOS Command-line utilities
- Task Runners Grunt and Gulp
- Applications on MacOS
- 1password on MacOS
- Data Backups on MacOS
- Manage Disk Space on MacOS
- Screen capture on MacOS
- Printing from macOS or Linux
- Ports open
- MacOS iPhone integration
- Windows on Apple MacOS
- Packer create Vagrant Windows image
- Remote into Windows
- Python on MacOS
- Maven on MacOS
- Ruby on MacOS
- Node on MacOS installation
- PHP on MacOS
- Java on MacOS
- Scala ecosystem
Others must know: please click to share:
Pyenv and Pipenv (on MacOS) was published on October 02, 2021 .
You might also enjoy (View all posts)
- Quantum (AI computing)
- OWASP
- Acronyms (and contractions)
Pyenv unable to detect installed python versions on MacOS Catalina
I have MacOS Catalina and I went ahead and did a brew install for the latest version of python 3.8.5. Then I discovered pyenv and installed that as well. I followed the steps on https://github.com/pyenv/pyenv#basic-github-checkout from number 3 but still can’t see any python versions in pyenv . I have both .zprofile and .zshrc files and am wondering if that’s causing issues. Here’s my echo $PATH —
/Users/pq0252/.pyenv/shims/shims:/Users/pq0252/.pyenv/shims/shims:/Users/pq0252/.pyenv/shims:/Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbinHere’s the pyenv version output:
pyenv versions * system (set by /Users/pq0252/.pyenv/shims/version)Here’s the .zprofile contents —
#Setting PATH for Python 3.8. #The original version is saved in .zprofile.pysave. PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:$" export PATHHere’s the .zshrc contents (this seems to be repeating the if condition, even though I only added it once which I am thinking has something to do with the step 3 on pyenv github where we are appending to it?).
export PYENV_ROOT="$HOME/.pyenv/shims" export PATH="$PYENV_ROOT:$PATH" export PIPENV_PYTHON="$PYENV_ROOT/python" echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\n$ if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fi if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fiShould I remove entries in .zshrc and instead add everything to .zprofile or is there something else I’m missing? python3 —version does show 3.8.5.
Установка и настройка Pуthon, Django и virtualenv на Mac OS
Я начал изучать возможности Django. Но раньше я работал только с DLE CMS и WordPress. Поэтому решил почитать инструкции по установке и настройке Джанго, с учетом того, что у меня Mac OS.
Стоит немного остановиться на том, что такое Django. Это достаточно мощный и уважаемый среди разработчиков фреймворк для создания сайтов, написанный на Python. Django считается очен быстрым и безопасным фреймворком, а благодаря своей модульности он очень гибкий и хорошо масштабируется.
Есть очень много разных туториалов по установке, настройке и запуску Django. Но часть из них или достаточно объемные, или упускают какие-то важные вещи. В этой статье я постараюсь описать основные шаги, необходимые для запуска проекта на Python-Django под Mac OS.
Основные шаги:
- Установка Homebrew.
- Установка Python 3.
- Установка virtualenv.
- Создание изолированного окружения для проекта.
- Запуск изолированного окружения.
- Установка Django.
- Создание проекта.
- Запуск проекта!
Установка Homebrew
Homebrew — бесплатная открытая система управления программными проектами, которая упрощает установку программного обеспечения на операционную систему Mac OS. Homebrew использует Github для расширения поддержки пакетов, за счет вклада пользователей.
Если у вас не установлен Hombrew, необходимо запустить в терминале команду:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"Установка Python3
brew install python3Изначально Mac OS имеет предустановленный python версии 2. Поэтому, послу установки 3 версии питона, для доступа именно к python3 необходимо запускать его из терминала с командой python3.
Чтобы проверить версию python, надо запустить в терминале команду
python3 --versionВы должны получить сообщение с версией установленного python.
Установка virtualenv
sudo pip3 install virtualenvvirtualenv — инструмент для создания изолированного виртуального окружения Python. Благодаря этому инструменту можно создать несколько разных проектов python, с разным набором библиотек на одном устройстве. Например, если вы захотите использовать разные версии одного и того же модуля в разных проектах.
После установки virtualenv мы установим все другие пакеты, в том числе и django в изолированные окружения.
Создание изолированного окружения для проекта
Создаем папку, в которой будет храниться проект. Пример команды в терминале.
mkdir project_testИ переходим в нее:
cd project_testСоздаем виртуальное окружение для проекта:
virtualenv ptest -p python3Где “ptest” — это название изолированного окружения, на ваше усмотрение.
Запуск изолированного окружения
После создания окружения, необходимо его активировать, чтобы установить все необходимые модули. Для этого запускаем в терминале команду:
source ptest/bin/activateЧтобы определить, в каком окружении вы находитесь, посмотрите на префикс в терминале, в круглых скобках будет указано название.
Так как изолированное окружение создавалось при помощи python3, в этом окружении можно запускать команды сразу через python, а не python3, так же как и pip, вместо pip3.
Чтобы завершить работу изолированного окружения, достаточно написать команду
deactivateУстановка Django
Снова запустим изолированное окружение и через pip установим django.
pip install Django==2.2Где “2.2” — необходимая версия джанго.
Создание проекта
Все готово для создания проекта. Достаточно написать в терминале (с запущенной виртуальной средой):
django-admin.py startproject project1Поздравляю, вы создали свой первый проект на Django. Структура папок будет такой:
project_test/ ----- (level1)
|-- project1/ ---- (level2)
| |-- project1/ ---- (level3)
| | |-- __init__.py
| | |-- settings.py
| | |-- urls.py
| | |-- wsgi.py
| +-- manage.py
+-- ptest/- project_test —домашняя папка проекта
- project1 — папка проекта django
- project1 — корневая папка
- ptest — виртуальная среда проекта
Запуск проекта
В Django встроен простой виртуальный веб-сервер. Не надо устанавливать никаких других программ на локальной машине. Чтобы его проверить, запустите в терминале команду:
python project1/manage.py runserverОсталось проверить что сервер запущен, для этого в браузере открываем адрес http://127.0.0.1:8000.
Поздравляю, вы запустили свой первый проект на Django!
