Setting up Python on Windows
There are many ways to set up Python on Windows—too many ways. According to the Zen of Python:
There should be one—and preferably only one—obvious way to do it.
In this spirit, I describe here what I think is the simplest way to set up Python on Windows, where “simplest” means:
- using pure Python, with no extra packages;
- enabling multiple versions of Python to exist side-by-side, without clobbering each other; and
- using no magic, meaning the user is in control and can understand everything (this is related to 1 above);
Assuming you have never installed Python, the basic steps are:
- disable the Windows Python installer;
- download Python—as many versions as you want—from python.org;
- install each version in your user directory, with the Python launcher, but without adding anything to your path; and
- using py.exe , the Python launcher built-in to Python on Windows, within each of your projects, create a virtual environment as a subfolder in the project folder, specifying the Python version needed.
I conclude with some tips on using VS Code and a discussion of alternative methods of setting up Python on Windows.
Step 1: Disable the Windows Python installer
If you type python or python3 at a command prompt in a new Windows 10 installation, you land at a link at the Microsoft Store for installing Python. This is supposed to make things easy for beginners. It sort of does, but at the expense of potentially making it harder to manage multiple Python versions. Installation via the Microsoft Store smells like magic to me, so I don’t recommend it.
To disable this behavior, go to Start→Manage App Execution Aliases and turn off the toggles for App Installer — python.exe and App Installer — python3.exe, like so:
Step 2: Download Python from python.org
To avoid magic, download Python directly. You can install as many versions as you like. The order of installation doesn’t really matter, though (as discussed below) it may affect the behavior of py.exe , the Python launcher.
Step 3: Install Python in a user directory, with launcher
By default, when you install Python with an installer from python.org:
- Python will be installed in a user-specific directory rather than a system directory,
- Python will install the Windows launcher, py.exe , for all users (in C:\Windows ), and
- Python will not change your system path.
Accept these defaults. The installation screen should look like this:
After you select Install now, the next screen will ask if you want to Disable path length limit so that your path can exceed the system’s 260-character limit. I suspect this is unnecessary, since we are deliberately not adding Python to the path. But I’m not sure there’s a downside. Use your judgment.
Note: The next time you install some version of Python, the Install launcher for all users option will probably be grayed out, because the launcher will already be installed. If it’s grayed out, that’s fine. If it’s not grayed out, leave it selected, and the launcher will be updated.
Step 4: Use py.exe to create virtual environments
The Python launcher py.exe allows you to easily work with multiple different versions of Python. Basic commands (executed at a command prompt):
- py — launches the latest version of Python you have installed.
- There’s a tiny bit of magic here. When you install a newer version of Python, the launcher will automagically update itself so that when py is run with no arguments, it launches the latest version of Python.
- You will typically not use this by itself, because you will be using py to create virtual environments, rather than to run Python outside of an environment.
- With no arguments, this launches the Python REPL. With arguments, this is how we execute modules or scripts. It’s the key to creating virtual environments.
Creating virtual environments with py.exe and venv
- At a command prompt, create a project directory and navigate into to it. For example (here > is the prompt):
- You can substitute any installed version for -3.9 in this statement (you don’t need to specify the minor version).
- The environment name p1_venv is arbitrary.
- This will create a subfolder \p1_venv within the C:\my_projects\project1 parent folder.
- This structure—a top-level project folder with a virtual environment in a subfolder—is the preferred structure for doing Python development with VS Code.
- There might be other good reasons for always using venv or .venv to name a virtual environment. Perhaps it makes other setup tasks easier. But I’ve never seen anyone explain the benefits (if they exist).
Using the virtual environment
If your virtual environment is at C:\my_projects\project1\p1_venv , activate it as follows:
You should now see the virtual environment name before the prompt, like so (assuming your working directory is also shown at the prompt):
To deactivate, just enter deactivate at the prompt.
Using Powershell aliases to simplify using virtual environments
Creating Powershell aliases can make using virtual environments easier. Building on the example above, you might put something like this in your Powershell profile (a user- and host-specific profile is at $profile.CurrentUserCurrentHost and is called Microsoft.PowerShell_profile.ps1 wherever it’s found 1 ):
Using VS Code with Python virtual environments
The VS Code Python extension is designed to work well with virtual environments, but I found the documentation confusing. While answering my own question on StackOverflow, I figured out what I think is a good workflow. This assumes you have already created your virtual environment in a subfolder within your project directory:
- At the command prompt, navigate to your project directory (the directory that contains your virtual environment). (You could create an alias for this navigation if you like.)
- From there, execute code .
This will open VS Code, using your project directory as a workspace. If you create or open a Python file in the workspace, VS Code will automatically detect and activate the virtual environment in the subfolder in the workspace (i.e., project directory).
You might be tempted to use a virtual environment as a project directory, that is, as the root of your workspace. Don’t do it. The VS Code documentation should say 2 ):
Note: Your Python virtual environment should always be a subdirectory within a VS Code workspace. Opening the virtual-environment folder directly, as the root of the workspace, might cause problems.
You can create a Python virtual environment within a workspace by using VS Code’s built-in terminal. But I prefer to create the environment first, outside of VS Code, because that way, I know exactly what’s happening.
If for some reason VS Code does not detect your virtual environment, you can manually direct VS Code to it by opening the command palette with Ctrl-Shift-P , entering Python: Select Interpreter , and navigating to python.exe found in the \Scripts subfolder of the virtual environment. You should only need to do this once.
Alternative methods for setting up Python on Windows
The pyenv project
There is a whole project, pyenv for Windows, specifically designed to allow you to manage multiple versions of Python on Windows. It’s an impressive piece of work, and if it interests you, check out a very detailed Real Python tutorial on using it.
I prefer not to use it for two reasons:
- I don’t see the need, given the existence of py.exe . And
- It only works well if you use it exclusively. For instance, if you have previously installed a Python version directly, without using pyenv , then pyenv will not detect the installed version.
Using venv or virtualenv (or something else)
Since Python 3.3, venv has been the tool in the Python standard libary for creating virtual environments. For simplicity’s sake, like the author of the second answer to this StackOverflow question, I (and apparently Guido van Rossum) prefer using it.
You will, however, see lots of references to using virtualenv for creating virtual environments. It existed before venv and is apparently your only option if you use Python 2.x. And pyenv includes even more related tools. These various tools are summarized in the first answer to the StackOverflow question cited above. I disagree with the answer, but it’s full of useful information.
2 Instead of this very clear warning, the VS Code documentation says:
Note: While it’s possible to open a virtual environment folder as a workspace, doing so is not recommended and might cause issues with using the Python extension. ↩
Brian Hagerty's tech blog
- Brian Hagerty's tech blog
Research notes about tech topics as they are learned: web development, web hosting, Python, Docker, etc. The whole potpourri.
Python и IDLE
Python — современный кросс-платформенный интерпретируемый язык программирования со строгой динамической типизацией. Отличается простым синтаксисом, лаконичностью программ, лёгкостью разработки и богатой библиотекой, позволяющей использовать Python для различных целей.
Большинство современных дистрибутивов Linux содержат интерпретатор Python, т.к. на языке Python написана многие приложения.
Просто Python — это интерпретатор программ, он необходим для запуска программ, написанных на языке Python. Для разработки программ как правило используют среды разработки, например, IDLE, Wing IDE, PyCharm, VS Code и т.д.
В настоящий момент разрабатывается ветка версии 3 языка Python, в 2022 году была выпущена новая версия 3.11. Версия 2 языка Python уже не поддерживается и не рекомендуется к использованию, но её иногда можно встретить, т.к. часть старых приложений может быть написана с использованием Python версии 2. Например, дистрибутив МОС содержит обе версии языка Python сразу после установки, если в консоли выполнить команду python2, то будет запущен интерпретатор версии 2.7.18, а для запуска интерпретатора Python версии 3 в МОС (и большинстве дистрибутивов Linux) используется консольная команда python3.
IDLE — простая среда разработки, «стандартная» для языка Python.
Содержание
Установка в МОС
Устанавливается автоматически при установке дистрибутива, вместе со средой IDLE. Ярлык для запуска IDLE в меню KDE находится в разделе «Разработка — IDE».
Интерпретатор языка Python версии 3 содержится в пакете python3, дополнительные модули языка Python версии 3 содержатся в пакетах с именами, начинающимися на python3-module-. Среда разработки IDLE содержится в пакете python3-tools. Установить пакеты можно используя пакетный менеджер Synaptic или командой консоли под пользователем root. Например, если среда IDLE по каким-то причинам не была установлена, её можно установить командой
Внимание! Пакеты, в названии которых есть python, не не python3 (например, python-modules, python-modules-pygtk) относятся к python версии 2 и нужны только для поддержки старых программ. Скорее всего, вам не нужно специально устанавливать эти пакеты).
Установка в Windows
В большинстве случаев можно использовать последнюю версию языка Python. Если открыть страницу https://www.python.org/downloads/ в браузере в системе Windows, то вы увидите надпись «Download the latest version for Windows» ниже которой будет кнопка со ссылкой на скачивание установщика последней версии под Windows. Если вы хотите другую версию языка Python или используйте страницу не в Windows, то откройте страницу https://www.python.org/downloads/windows/, найдите версию Python, которая вам нужна, скачайте файл «Download Windows installer (64-bit)».
Дистрибутив Python для Windows уже содержит среду разработки IDLE, поэтому устанавливать IDLE дополнительно не требуется.
Вот прямые ссылки на скачивание некоторых последних версий:
Скачанный дистрибутив запустите с правами администратора.
При установке нужно выбрать следующие опции.
На первом экране установки поставить галочку в пункте «Add python.exe to PATH» внизу страницы. Также убедитесь, что стоит галочка в пункте «use admin privileges when installing py.exe». Для этого необходимо запускать установщик с правами администратора.
Также обратите внимание на этом окне на пусть установки Python ниже кнопки «Install now». По умолчанию установка производится в профиль данного пользователя (C:\Users\. ), а нужна установка для всех пользователей. Нажмите на кнопку «Customize installation», в следующем окне «Optional features» нажмите на «Next» и в окне «Advanced options» нужно поставить галочку в пункте «Install Python 3.11 for all users». После этого путь для установки внизу окна изменится на C:\Program Files\Python311.
Убедитесь в том, что пусть для установки Python выглядит как C:\Program Files\Python311 (числа в конце могут быть другими при установке версии, отличной от 3.11) и нажмите на кнопку Install.
Если в конце установки вы видите сообщение с кнопкой «Disable path length limit», нажмите на эту кнопку. Затем нажмите на Close.
Проверка работы среды IDLE
Запустите среду IDLE из меню операционной системы. Убедитесь, что версия среды в заголовке окна и версия языка после слова «Python» в белом поле нужная (например, версия 3, а не версия 2).
Выберите пункт меню «File — New File». Откроется окно редактора программы. Вставьте в окно редактора текст программы.
Сохраните файл. Выберите в меню команду «Run — Run Module» или нажмите на F5.
После запуска программы в окне IDLE Shell должен появиться текст «Hello, world!».
IPython
IPython (англ. Interactive Python) — интерактивная оболочка для языка программирования Python, которая предоставляет расширенную интроспекцию, дополнительный командный синтаксис, подсветку кода и автоматическое дополнение. Является компонентом пакетов программ SciPy и Anaconda.
Python Disable Path Length Limit in Windows
“Disable the path limit length” is recommended after Python setup is successful.
The reason behind this [“Disable the path limit length“] is, if Python was installed in a windows OS directory with a path length greater than 260 characters, adding it to the path could fail. This is because, Windows OS, by default has the Maximum Path allowed for PATH variables as 260 characters.
“Disable the path limit length” disables the MAX_PATH variable limit on Windows, therefore allowing you to use long Path variables (longer than 260 characters).
In Linux-based operating systems and macOS, the Path Length is not an issue.
Right now, Windows has the ability to accomodate long path lengths, so there is really no need to worry. The path length that is currently supported on Windows OS is 32,767, and it has been for more than 2 decades.
Disable Path Length Limit in Python
In programming, we deal with problems where we have to work with external files and modules. Therefore we need to know the location of files stored on the disk specified by the file path.
A very common error raised in Python during compilation is about file name or path length of file being too long . This is because the pathname or the filename can only be of a specific length which is around 260 characters. This issue is not a problem for macOS or Linux-based systems and exists only in Windows. This limit was put in place due to the path limit restriction in the initial versions of Windows OS.
Please enable JavaScript
In Python, we get the option to disable this length limit after installing Python. Enabling this might help cross-platform compatibility between programs and allow the program to run normally on an older version of Windows.
To overcome such issues, we can shorten the path or filename to meet the required length.
However, if someone wants to remove this limit, then it is not necessarily a bad thing. If someone has installed Python in a directory that exceeds the path length limit, then it is recommended to disable it when the option is provided.
Given that no one hardly works on initial Windows versions, disabling the path limit does not have any harmful effect while running your code and can also help in debugging to avoid such issues.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.