Setting Up pyenv-win and Managing Python Versions with PowerShell

What is pyenv?

pyenv is a tool that allows you to easily install and switch between multiple versions of Python. For example, you can use Python 3.9 for one project and Python 3.7 for another without any issues.

Why is pyenv useful?

Manage multiple Python versions:

Typically, when you install Python, you can only use one version at a time. However, some projects may require different versions of Python. With pyenv, you can easily install and switch between multiple Python versions.

Doesn’t affect the system Python:

The Python versions managed by pyenv are kept separate from the system Python, so there’s no need to worry about affecting the Python version that comes with your operating system.

Easily switch between versions:

You can specify different Python versions for each project and easily switch between them with a single pyenv command.

The significance of not affecting the system Python:

Independent management: pyenv creates its own environment within the user’s home directory to manage Python versions. This means the versions of Python and libraries installed via pyenv do not interfere with the system-wide Python (the system Python).

Security: The system Python might be required by certain OS tools or scripts. By using pyenv, you can freely install different versions of Python or switch between them for each project without altering these system dependencies.

Maintaining compatibility: If you want to use a new version of Python for a specific project, you can test it using pyenv without affecting the system Python. Conversely, even if the system Python is updated, it won’t affect projects managed by pyenv.

Basic usage of pyenv

Installation:

On Linux and macOS, pyenv can be installed via the terminal, while on Windows, it’s installed using a tool called pyenv-win.

After installation, you can use the pyenv install command to install any version of Python you need.

Switching versions:

To change the default Python version to 3.9.1, you can enter pyenv global 3.9.1.

If you want to set a specific version for a project, navigate to the project directory and enter something like pyenv local 3.8.5. This will switch the Python version used within that directory.

Checking the current version:

To check the Python version you’re currently using, type pyenv version.

Important notes

Windows users should use pyenv-win instead of pyenv. Although the commands are almost the same, pyenv-win is tailored specifically for Windows.

Key point:

You can install new versions of Python using pyenv-win without relying on the version of Python installed on Windows itself. In other words, even if an old version of Python is installed on Windows, you can still manage and install the latest Python versions with pyenv-win.

In simple terms, even if the version of Python installed on Windows is outdated, you can still manage and install newer Python versions without any issues using pyenv-win.

It is strongly recommended to follow the official GitHub repository for installing pyenv or pyenv-win. Here’s why:

Why is it better to follow GitHub for installation?

Access to the latest updates:

The GitHub repository is regularly updated by the developers with the latest versions, bug fixes, and security updates. By following the official documentation, you can always install pyenv in the most up-to-date and secure way.

Official installation instructions:

GitHub provides detailed official installation instructions, covering correct configurations and dependencies. By following these instructions, you can avoid incorrect settings and unnecessary troubles.

Troubleshooting:

If you encounter any problems during installation, you can find similar issues reported by other users in the “Issues” or “Discussions” sections on GitHub, along with possible solutions. Often, other users or developers have already provided resolutions.

Community support:

The GitHub repository also offers support and advice from other users and developers. By posting questions or concerns about the installation, you can receive assistance from the community.

So, let’s proceed with the installation by referring to the following page:

https://github.com/pyenv-win/pyenv-win

The main reason I chose to use pyenv is that it allows me to change the Python version based on the project (directory) I’m working on.

.
├── global (Python 3.10)
│   
├── project1/
│   └── .python-version (Python 3.12)
│
├── project2/
│   └── .python-version (Python 3.8)
│
└── project3/
    └── .python-version (Python 3.9)

Explanation

  • global: The Python version set globally is 3.10.
  • project1: Within the project1 folder, Python 3.12 is used as specified by pyenv local.
  • project2: Within the project2 folder, Python 3.8 is set.
  • project3: Within the project3 folder, Python 3.9 is set.

Here is a concrete example:

.
├── global (Python 3.10)
│   
├── stable-diffusion/
│   └── .python-version (Python 3.9)
│
├── flask-web-app/
│   └── .python-version (Python 3.8)
│
└── data-analysis/
    └── .python-version (Python 3.12)

The GitHub page mentions entering commands using PowerShell, but we’ll use the terminal in VS Code instead. This is described as a quick installation.

Invoke-WebRequest -UseBasicParsing -Uri "https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1" -OutFile "./install-pyenv-win.ps1"; &"./install-pyenv-win.ps1"

However, an error occurred:

Directory: C:\Users\minok

Mode LastWriteTime Length Name
—- ————- —— —-
d—- 2024/08/16 17:18 .pyenv
Microsoft.PowerShell.Archive\Expand-Archive : The module ‘Microsoft.PowerShell.Archive’ could not be loaded. For more details, please run ‘Import-Module Microsoft.PowerShell.Archive’.
At line:1 char:1

Microsoft.PowerShell.Archive\Expand-Archive -Path “C:\Users\minok.py …

~~~~~~~~~~~

CategoryInfo : ObjectNotFound: (Microsoft.Power…\Expand-Archive:String) [], CommandNotFoundException

FullyQualifiedErrorId : CouldNotAutoLoadModule

Move-Item: C:\Users\minok\install-pyenv-win.ps1:126:5
Line |
126 | Move-Item -Path “$PyEnvDir\pyenv-win-master*” -Destination “$PyE …
| ~~~~~~~~~~~~~
| Cannot find path ‘C:\Users\minok.pyenv\pyenv-win-master’ because it does not exist.
Remove-Item: C:\Users\minok\install-pyenv-win.ps1:127:5
Line |
127 | Remove-Item -Path “$PyEnvDir\pyenv-win-master” -Recurse
| ~~~~~~~~~~~
| Cannot find path ‘C:\Users\minok.pyenv\pyenv-win-master’ because it does not exist.
pyenv-win is successfully installed. You may need to close and reopen your terminal before using it.

Based on the message, it seems that some errors occurred during the installation process of pyenv-win, but it eventually displayed “pyenv-win is successfully installed.” This suggests that the installation may have partially succeeded.

Summary of Errors and Solutions

Microsoft.PowerShell.Archive Module Loading Error:

This indicates that the Microsoft.PowerShell.Archive module failed to load when attempting to use the Expand-Archive command in PowerShell. This module is used for tasks like extracting ZIP files.

Solution: You need to manually import the module by running the command Import-Module Microsoft.PowerShell.Archive. After that, try running the installation script again.

Move-Item and Remove-Item Errors:

These errors indicate that the file move and delete operations failed because the specified directory does not exist. This is likely due to the previous failure of Expand-Archive, which means the necessary files were not extracted.

Next Steps

Restart the Terminal:

Following the message, close the terminal and reopen it to see if the pyenv command is recognized.

Check pyenv:

In the terminal, type pyenv --version to check if pyenv-win has been installed correctly.

Import the Module and Re-run the Script:

If pyenv --version does not work, run the following command to import the module, then try executing the installation script again: Import-Module Microsoft.PowerShell.Archive.

After that, run the installation script again, but the following error occurred:

/install-pyenv-win.ps1″ -OutFile “./install-pyenv-win.ps1″; &”./install-pyenv-win.ps1″
New-Item: C:\Users\minok\install-pyenv-win.ps1:115:5
Line |
115 | New-Item -Path $PyEnvDir -ItemType Directory
| ~~~~~~~~~~~~
| An item with the specified name C:\Users\minok.pyenv already exists.
Microsoft.PowerShell.Archive\Expand-Archive : The module ‘Microsoft.PowerShell.Archive’ could not be loaded. For more details, please run ‘Import-Module Microsoft.PowerShell.Archive’.
At line:1 char:1

Microsoft.PowerShell.Archive\Expand-Archive -Path “C:\Users\minok.py …

~~~~~~~~~~~

CategoryInfo : ObjectNotFound: (Microsoft.Power…\Expand-Archive:String) [], CommandNotFoundException

FullyQualifiedErrorId : CouldNotAutoLoadModule

Move-Item: C:\Users\minok\install-pyenv-win.ps1:126:5
Line |
126 | Move-Item -Path “$PyEnvDir\pyenv-win-master*” -Destination “$PyE …
| ~~~~~~~~~~~~~
| Cannot find path ‘C:\Users\minok.pyenv\pyenv-win-master’ because it does not exist.
Remove-Item: C:\Users\minok\install-pyenv-win.ps1:127:5
Line |
127 | Remove-Item -Path “$PyEnvDir\pyenv-win-master” -Recurse
| ~~~~~~~~~~~
| Cannot find path ‘C:\Users\minok.pyenv\pyenv-win-master’ because it does not exist.
pyenv-win is successfully installed. You may need to close and reopen your terminal before using it.

Based on this message, it seems that some parts of the pyenv-win installation are still not working correctly. The issue with the Microsoft.PowerShell.Archive module has not been resolved, so the ZIP file could not be extracted, leading to related errors continuing to occur. I will restart VS Code.

Next Steps

Check the PowerShell Version: First, check the version of PowerShell. The Microsoft.PowerShell.Archive module is included by default in PowerShell 5.1 and later, so if your PowerShell version is outdated, you may need to upgrade. You can check the version with the following command: $PSVersionTable.PSVersion

Manual Module Import: If your PowerShell version is 5.1 or higher, try the following command to see if the module can be imported correctly: Import-Module -Name Microsoft.PowerShell.Archive. If this resolves the error, try running the installation script again. However, since the Microsoft.PowerShell.Archive module is still not loading, the ZIP file could not be extracted, and a series of related errors are occurring. Yet, the message “pyenv-win is successfully installed” is still being displayed.

Therefore, I checked the PowerShell version, and it meets the required conditions.

PS C:\Users\minok> $PSVersionTable.PSVersion

Major Minor Patch PreReleaseLabel BuildLabel
—– —– —– ————— ———-
7 4 4

Next, when I checked the environment variables, it seems that the following paths have been added:

C:\Users\minok\.pyenv\pyenv-win\bin
C:\Users\minok\.pyenv\pyenv-win\shims

Next, I will check where the Windows home directory is located. The result is as follows, and it is the location where the commands were executed:

PS C:\Users\minok> cd\
PS C:> cd $HOME
PS C:\Users\minok>

I confirmed where the home directory is located. However, upon checking its contents, I found that it was empty. This means that I was checking the paths that had been added to the environment variables.

PS C:\Users\minok> cd .pyenv
PS C:\Users\minok.pyenv> dir
PS C:\Users\minok.pyenv>

Therefore, I decided to manually clone the repository. While in the home directory, I entered the following command. This command downloads the necessary files into the C:\Users\minok\.pyenv\pyenv-win folder.

git clone https://github.com/pyenv-win/pyenv-win.git $HOME\.pyenv\pyenv-win

Now, I will check the version.

PS C:\Users\minok.pyenv> pyenv version
3.7.4 (set by C:\Users\minok.pyenv\.python-version)

It finally worked. However, even if it works in VS Code, it may still result in the following error in PowerShell:

PS C:\Users\minok> pyenv version
pyenv : File C:\Users\minok\.pyenv\pyenv-win\bin\pyenv.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see “about_Execution_Policies” (https://go.microsoft.com/fwlink/?LinkID=135170).
At line:1 char:1

pyenv version

~

CategoryInfo : SecurityError: (:) [], PSSecurityException

FullyQualifiedErrorId : UnauthorizedAccess

After some investigation, I discovered that the issue occurs because PowerShell’s execution policy does not allow scripts to run. I will address this issue.

Steps to Change the Execution Policy

Check the Current Execution Policy: To check the current execution policy, run the following command in PowerShell:

Get-ExecutionPolicy

This will display the current execution policy.

Change the Execution Policy: To allow script execution, run the following command. Typically, you would set it to “RemoteSigned” or “Unrestricted”:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

This allows local scripts to run, and remote scripts can be run if they are signed.

Verification: After changing the execution policy, run the following command to check the version of pyenv:

pyenv --version

or

pyenv version

Important Note:

When changing the execution policy, you may need administrator privileges. Please run PowerShell as an administrator before executing the above command.

You can also check the execution policy again after making the changes.

For reference, PowerShell will display the following:

PS C:\Users\minok> pyenv version
No global/local python version has been set yet. Please set the global/local version by typing:
pyenv global
pyenv global 3.7.4
pyenv local
pyenv local 3.7.4

In some projects, a specific version of Python may be required. In such cases, you can change the Python version only for a specific project (folder) using the pyenv local command. When you run this command, the specified Python version will only apply within that directory. For example, let’s explain using Python version 3.12.

Step 1: Install Python 3.12

First, use pyenv-win to install Python 3.12.

Open the terminal:

Open PowerShell or the terminal in VS Code.

Check available Python versions: Enter the following command to display a list of available Python versions for installation:

pyenv install --list

Find version 3.12.0 in the list.

Install Python 3.12: Enter the following command to install Python 3.12:

pyenv install 3.12.0

This will install Python 3.12.0.


Step 2: Use Python 3.12 for a specific project

Next, set Python 3.12 to be used only within a specific project folder.

Move to the project folder: Navigate to the folder where you want to change the Python version. For example, to move to the sample folder, use the following command:

cd C:\youtube\sample

Set Python 3.12: In the project folder, run the following command to set Python 3.12 for that folder:

pyenv local 3.12.0

This ensures that Python 3.12.0 is only used within this folder.


Step 3: Verify the settings

Finally, verify that the settings have been applied correctly.

Run the verification command: Enter the following command to check the current Python version:

pyenv version

If it displays 3.12.0 (set by <project folder path>), the setup was successful.

Note: There is also a command called pyenv versions, which can easily cause confusion with pyenv version because they are similar.


“Managing Python versions with pyenv: Explaining Common Beginner Confusions”

pyenv is a convenient tool for managing multiple versions of Python. However, beginners may often get confused between the pyenv version and pyenv versions commands. Here, we explain the usage of each command and how to efficiently manage Python versions.


The difference between pyenv version and pyenv versions

Using pyenv version:

This command is used to check which version of Python is currently being used. For example, it can quickly show which Python version is active for a specific project.

Example:

pyenv version
3.10.0 (set by C:\Users\minok\.pyenv\version)

Using pyenv versions:

This command lists all Python versions managed by pyenv. It allows you to see all installed Python versions at a glance.

Example:

pyenv versions
3.7.4
* 3.10.0 (set by C:\Users\minok\.pyenv\version)
3.12.0

“Choosing the Right Command for Different Situations”

When to use pyenv version:

Use this when you want to check which Python version is being used in the current project. By navigating to the desired folder and running this command, it will display the Python version set for that folder.

When to use pyenv versions:

Use this when you want to check all the installed Python versions. It’s best to run this in the home directory or a directory not associated with any specific project.


“Tips to Avoid Confusion”

Using pyenv global:

If you want to set a Python version for the entire system, use pyenv global. This will ensure that the chosen version is used as the default in any directory.

Navigating directories and running commands:

Since the results of pyenv versions can vary depending on where you run it, reviewing the output while working will help deepen your understanding.


“Summary and Next Steps”

Understanding how to manage Python versions with pyenv allows you to easily configure different environments for each project. Even beginners can confidently manage Python versions by following this guide.

Next, let’s dive deeper into how to switch Python versions for specific projects.


Bonus: Three Easy-to-Remember Examples

pyenv version explained:

Usage: This command is used to check the Python version currently in use.

How to remember: Think of “version” as “Which one now?”. Running this command displays the Python version currently being used.

When to use: Use this command when you want to check the Python version in use.


pyenv versions explained:

Usage: This command lists all Python versions managed by pyenv.

How to remember: Think of “versions” as “All versions”. Running this command displays a list of all installed Python versions.

When to use: Use this command when you want to check all installed Python versions.


pyenv version: Think of it as checking the tool you are currently using.

Example: Use pyenv version to check which Python version (tool) you are currently working with.

pyenv versions: Think of it as checking the entire toolbox.

Example: Use pyenv versions to see all the Python versions (tools) available in your toolbox.

Example for pyenv version:

“When working on Project A, I use pyenv version to check which Python version I am using.”

Example for pyenv versions:

“Next, I use pyenv versions to list all installed Python versions to see what is available.”

Please share if you like it!
TOC