Setting environment variables in Python is an essential skill for developers, allowing them to manage and streamline the configuration of their applications.
You’re able to set, store and easily modify these variables without altering the application’s core functionality.
You can set environment variables in Python using the os module, which provides a simple interface for working them. By using this module, developers can quickly set and get environment variables, making their programs more versatile and ideally suited to changing development or production environments.
Throughout this article, we’ll discuss effective techniques for setting and accessing environment variables within your Python code and leveraging their potential to produce cleaner, more flexible applications.
From using the os module to various command line tools, this guide will provide valuable insights to streamline your development process and promote best practices across your projects.
Let’s dive in!
What is an Environment Variable?
Environment variables are variables set outside the program in its running environment by the user, operating system (OS), etc.
They are key-value pairs used by operating systems to store information about the environment, such as paths and configuration settings.
Some common environment variables related to Python include PATH, PYTHONPATH, and PYTHONHOME.
Other use cases include API keys, database credentials, and other sensitive information stored outside of the code to enhance security and maintainability.
For example, if we’re pulling data from an API like the GoogleNews API in our video below, we can use environment variables to store the API keys.
By doing this, we avoid hardcoding the keys.
Scope of Environment Variables
There are two types of environment variables: system variables and user variables. System variables are globally accessible for all users, while user environment variables are only accessible to the specific user account.
For example, the PATH variable is one of the critical system environment variables that determine the directories where the OS searches for executables, like the Python interpreter.
To effectively work with Python, it’s essential to add the interpreter’s location to the PATH environment variable.
This allows you to run Python commands from the command line without specifying the full path to the Python executable. You can typically add Python to the PATH when installing it, or you can manually modify it later.
How to Set Environment Variables in Python
There are two methods you can use in setting environment variables in Python. You can either use the OS module or the python-dotenv library.
Let’s look at how they work:
1. How to Set Environment Variables Using the OS Module
The OS module in Python provides a convenient and portable way to interact with the operating system. The os.environ dictionary is an essential part of this module, as it allows Python programs to access and modify environment variables.
It represents the environment variables of the operating system. We can use this dictionary to get, set, and modify environment variables in Python.
Let’s take a look at how it works:
1. Setting Environment Variables
To set an environment variable, you can assign a value to a specific key in the os.environ dictionary. Make sure that the value is always a string. Here’s an example:
import os
os.environ['MY_VARIABLE'] = 'hello'
You can also use it to modify the value of an existing environment variable.
2. Retrieving Environment Variables
To retrieve environment variables, you can use the os.environ dictionary as a regular Python dictionary. To get the value of a specific environment variable, simply use the variable’s name as the key.
For example:
import os
home_dir = os.environ['HOME']
If the environment variable exists, it returns its value. If it doesn’t, it returns a KeyError exception.
Alternatively, you can use the os.getenv() and os.environ.get() methods to access environment variables, avoiding a KeyError when the variable does not exist:
#Both of these environment varaibles don't exist.
user = os.getenv('API_USER')
password = os.environ.get('API_PASSWORD', 'default value')
Output:
None
default value
They return None if the variable doesn’t exist. You can also set a default value as the second argument in both functions if the environment variable doesn’t exist.
Remember that the OS module is an important tool for managing environment variables in Python programs. By using the os.environ dictionary to set and get variables, you can confidently interact with the operating system in a portable and clear manner.
2. How to Set Environment Variables Using the Dotenv Package
The Python-dotenv package is a valuable tool that can help you manage environment variables in your Python applications. It allows you to store key-value pairs in a .env file, keeping sensitive information separate from your application code and preventing accidental leaks or hard-coding of variables.
Also, setting multiple environment variables with the os.environ library can take quite a bit of time. By using a .env file, you can load multiple environment variables into your running environment immediately after your program starts running.
Let’s look at how you can use it:
1. Loading Environment Variables with Load_Dotenv
To begin, ensure that the Python-dotenv package has been installed. If you haven’t done so already, you can install it using the pip install python-dotenv command on your terminal.
Once installed, you can import the load_dotenv function from the package and use it to load the key-value pairs from your .env file as environment variables. These variables can then be accessed using Python’s os module.
Here’s a brief example:
from dotenv import load_dotenv
import os
load_dotenv()
access_token = os.getenv("ACCESS_TOKEN")
secret_token = os.getenv("SECRET_TOKEN")
In this example, the .env file should be located in your project directory and should contain the key-value pairs for ACCESS_TOKEN and SECRET_TOKEN.
Note: When using environment variables in your Python project, it’s important to keep security in mind. Since the .env file may contain sensitive information, such as API keys or secrets, it is essential that you exclude it from version control systems such as Git.
To do this, simply add the .env file to your .gitignore file:
# .gitignore
.env
By doing so, you ensure that the .env file is not accidentally committed to your Git repository, keeping your sensitive data secure. You can read more about this module in our article on Python-Dotenv: Setting Environmental Variables.
How to Set Environment Variables via the Command Line
You can set environment variables for your program directly from your command line interface. This method provides an alternative to setting environment variables via Python.
You can also use them to set permanent environment variables system-wide. Here’s how you can achieve this in various operating systems:
1. How to Set Environment Variables in Windows
In Windows, you can set environment variables permanently using the setx command in the Command Prompt. Here’s an example of setting the PYTHONPATH:
setx PYTHONPATH "C:\path\to\your\python\directory"
This will make the PYTHONPATH environment variable permanent. To temporarily set an environment variable, use the set command:
set PYTHONPATH=C:\path\to\your\python\directory
Alternatively, you can set environment variables through the System Properties window, under “Environment Variables.“
After setting the environment variable, you can retrieve them using the echo %<variable-name>% format. For example:
set PYTHONPATH=C:\path\to\your\python\directory
echo %PYTHONPATH%
Output:
To list all environment variables, you can simply run the set command in the terminal.
2. How to Set Environment Variables in Unix (Linux & macOS)
In Unix-based operating systems such as Linux and MacOS, the export command is used to set environment variables. Here’s an example of setting the PYTHONPATH:
export PYTHONPATH="/path/to/your/python/directory"
This will set the environment variable for the current session. Once you terminate the shell, the environment variable will be deleted. To make it permanent, you can add the export command to your shell configuration file (e.g., .bashrc, .zshrc, or .profile).
To get the value of an environment variable, use the echo command:
echo $PYTHONPATH
To list all the environment variables, you can use the printenv command.
What is the Scope of an Environment Variable in Python?
In Python, environment variables’ scope is limited to the process they belong to and any subprocesses spawned by the parent process.
When you modify an environment variable within a Python script, its changes only affect the current process and the spawned subprocesses, but not the calling process or the entire system.
For example, you can temporarily modify the current process’s environment using Python’s os module:
import os
# Store initial PATH value
initial_path = os.environ['PATH']
# Set a new PATH value for the process
os.environ['PATH'] = '/new/directory:' + initial_path
# Perform actions using the updated PATH
# Restore initial PATH value
os.environ['PATH'] = initial_path
It’s important to note that modifying environment variables within a Python script will not change the overall system or user environment permanently.
This temporary modification mainly helps in managing dependencies and enabling specific behaviors for sub-processes, such as changing the Python startup behavior or configuration.
Advanced Environment Management in Python
Having navigated the foundational concepts of environment management in Python, you’ve established a strong footing in ensuring project consistency and avoiding dependency conflicts.
However, as we venture into more intricate and large-scale projects, a deeper understanding becomes paramount. This section builds upon that foundation, diving into the nuances and sophisticated techniques that cater to the multifaceted demands of complex Python endeavors.
1. Handling Newlines in Environment Variables
When working with environment variables in Python, you might encounter issues with newline characters. Newlines can cause unexpected behavior, especially when passing environment variables to subprocesses. Therefore, it’s essential to handle them correctly.
You can remove newlines using the str.strip() function:
import os
raw_value = os.environ.get("MY_VARIABLE", "")
clean_value = raw_value.strip()
2. Default Values in Python Code
It’s common to use default values for environment variables in case they aren’t set in the system environment. This can be done using the os.environ.get() method or the os.getenv() function:
import os
# Using os.environ.get()
default_value = "default"
my_var = os.environ.get("MY_VAR", default_value)
# Using os.getenv()
another_var = os.getenv("ANOTHER_VAR", default_value)
Both methods retrieve the value of the environment variable if it exists, else return the specified default value.
3. Working with Child Processes
When creating subprocesses in Python, you might need to pass environment variables to them. The subprocess module provides an easy way to do this:
import os
import subprocess
# Set environment variables
os.environ["API_USER"] = "username"
os.environ["API_PASSWORD"] = "secret"
# Pass environment to child process
env = os.environ.copy()
result = subprocess.run(["your_command"], env=env)
In the above example, the os.environ.copy() function is used to create a copy of the current environment, which is then passed to the child process.
This method enables the child process to inherit the environment variables from the parent process while avoiding inadvertent changes to the global system environment.
Final Thoughts
The importance of configuring environment variables in Python can’t be overstated. Through the utilization of the os and python-dotenv modules, this process remains both accessible and efficient.
In a digital landscape where adaptability is key, Python’s elegant approach to managing environment variables underscores its position as a language of choice for pragmatic and effective programming.
That’s the end of our article on environment variables in Python. If you enjoyed be sure to read through our article on How to Delete Files from Python: 6 Easy Methods Explained.
Frequently Asked Questions
What is the proper way to set environment variables permanently in Linux?
In Linux, you can set environment variables permanently by adding export statements to the ~/.bashrc or ~/.profile file. Open the file with a text editor and append the following line:
export MY_VARIABLE=my_value
Save and exit the file. To apply the changes, either restart the terminal or use the command source ~/.bashrc or source ~/.profile.
What is the method to print all environment variables in Python?
To print all environment variables in Python, you can iterate through the os.environ dictionary after importing the os module:
import os
for key, value in os.environ.items():
print(f"{key}: {value}")
Do Python environment variables work in a virtual environment?
Yes, environment variables in Python work can work in a virtual environment. You can access and set them in the same way as in a regular environment.
You can even add the environment variable into the virtual environment’s activate.bat file for easy loading. This way, every time you load up the virtual environment, the program sets the environment variable.
You can append the export statement at the bottom of the script. For example:
export KEY = VALUE
Are environment variables set with Python?
No, environment variables set with Python are not permanent. They do not persist outside of the Python process.
Once the script or shell stops running, the environment variables are deleted or reverted to the system defaults.
In this post, you’ll learn about how to use environment variables in Python on Windows, macOS, and Linux. Environment variables in Python enable you to write smoother workflows and more secure code.
You’ll learn why environment variables are useful to learn and how to implement them. You’ll learn how to get and set environment variables in Python. You’ll also learn how to implement Python environment variables safely in source control management tools like Github.
By the end of this tutorial, you’ll have learned:
- What environment variables in Python are and why you’ll want to use them
- How to get and set environment variables in Python using Windows, macOS, and Linux
- How to improve the environment variable workflow with the
dotenv
library - How to safely store environment variables when working with source control management tools like Github
Table of Contents
Python environment variables are variables that exist outside of your code and are part of your system’s or current user’s configurations. Why would you want to use environment variables? Environment variables provide the opportunity to make your code:
- More streamlined – by not needing to repeat constants such as API keys across multiple files. Similarly, using environment variables gives you the opportunity to configure your code so it can be tailored to a particular user running your code. For example, if your code is used by multiple people, the user’s path can be accessed from the environment.
- More secure – by not exposing secure keys or user configurations within your code. This allows you to share code that relies on API keys or other secure information without needing to expose that code. This prevents others from ready these secure pieces of information.
Environment variables represent key-value pairs of data that can be accessed by your code. As you’ll learn later, they can be accessed just like any dictionary value.
When To Use Python Environment Variables
Environment variables should be used when a variable changes with the environment (such as when a different user runs the code). This means that the best use cases are when the code would otherwise need manual updating when run in a different environment.
Similarly, environment variables should be used when secure data are implemented in a shared piece of code (or code shared to a source control management tool like Github). This allows you to embed secure information outside the code, while still being able to run your code.
When you first learn about environment variables, it may seem like a good idea to use them for everything. Following the guideline mentioned above sets a good standard for when to use them.
How to Get Environment Variables in Python
Environment variables can be accessed using the os
library. In particular, they’re stored in the environ
attribute. Because the os
package is part of the standard Python library, you don’t need to install anything extra in order to get it to run.
In a later section, you’ll learn how to use the dotenv
module to manage environment variables more easily. For now, let’s take a look at how you can get all environment variables using the os
library.
How to See All Python Environment Variables
The easiest way to get all the environment variables available is to print out the os.environ
attribute. In order to do this, you’ll need to first import the library. Let’s see what this looks like:
# Getting All Environment Variables Using os
import os
print(os.environ)
# Returns:
# environ({'TERM_PROGRAM': 'vscode', ...})
I have truncated the returned value above to make it more readable. Running this on your machine will likely display a large amount of variables.
We can check the type of this variable to see what it is:
# Checking the Type of the os.environ
import os
print(type(os.environ))
# Returns
# <class 'os._Environ'>
In the next section, you’ll learn how to get a single environment variable in Python.
How to Get a Single Environment Variable in Python
Because the returned value of the os.environ
attribute is a dictionary-like structure, we can access a particular variable by using its key. For example, if we wanted to get the environment variable for 'USER'
we could access it as we would any other dictionary’s value:
# Getting a Single Environment Variable in Python
import os
print(os.environ['USER'])
# Returns: datagy
Now, what would happen if we tried to access a variable that didn’t exist? Let’s try getting the environment variable for 'nonsense'
:
# Getting an Environment Variable that Doesn't Exist
import os
print(os.environ['nonesense'])
# Returns: KeyError: 'nonsense'
We can see that this raises a KeyError
. If we don’t want our program to crash, we can use the .get()
method to safely return None
if no value exists. Let’s see what this looks like:
# Returning None if No Environment Variable Exists
import os
print(os.getenv('nonsense'))
# Returns: None
In the next section, you’ll learn how to check if an environment variable exists in Python.
How to Check if an Environment Variable Exists in Python
Because the returned value from the os.environ
attribute is dictionary-like, you can use the in
keyword to check whether or not an environment variable exists in Python. Let’s see how we can check if the variable 'USER'
exists on the environment using an if-else
block.
# Checking if an Environment Variable Exists in Python
import os
if 'USER' in os.environ:
print('Environment variable exists!')
else:
print('Environment variable does not exist.')
# Returns:
# Environment variable exists!
Using this conditional allows you to safely run code to see if an environment variable exists. If the variable doesn’t exist, you could, for example, prompt the user for input before continuing.
In the following section, you’ll learn how to return a default value if one doesn’t exist.
How to Return a Default Value for Environment Variables If One Doesn’t Exist
If no value exists for an environment variable, you may want to pass in a default value. This can also be done by using the .getenv()
method. By passing in a second parameter, a default value can be returned if a variable doesn’t exist.
Let’s see what this looks like:
# Returning a Default Value When a Variable Doesn't Exist
import os
print(os.getenv('nonsense', 'default value'))
# Returns: default value
In the next sections, you’ll learn how to set environment variables.
How to Set Environment Variables in Python
Now that you know how to get environment variables using Python, in this section, you’ll learn how to set the values for new or existing variables. Because this process is different for Windows and macOS / Linux, the process is split across two different sections.
How to Set Environment Variables in Python Using macOS And Linux
To set an environment variable in Python using either macOS or Linus is to use the export
command in a shell session. For example, if we wanted to set the variable of API_KEY to be equal to '123acb'
, we could write the following:
# Setting an Environment Variable
export API_KEY = '123abc'
When you run this code in your terminal, the environment variable will be set globally for all programs for that session. When you close your terminal, the environment variables are lost again.
If you only wanted to set the environment variable for a particular script, you can do this as well from the shell command. Simply change the command to this:
# Setting an Environment Variable
API_KEY = '123abc' python myscript.py
How to Set Environment Variables in Python Using Windows
Windows provides very similar ways to set environment variables in Python. Similar to macOS and Linux, you can set the variables for a single session by using the command prompt. Rather than using export
, you use the word set
. Let’s take a look:
# Setting an Environment Variable
set API_KEY = '123abc'
Instead, if you’re using the PowerShell console, you need to use the following code:
# Using PowerShell to Set an Environment Variable
$Env:API_KEY = '123abc'
In the following section, you’ll learn a much easier way to set and manage environment variables, using the dotenv
library.
How to Use dotenv in Python to Work with Environment Variables in Python
Using the terminal or command prompt to manage environment variables can be a time-consuming and, frankly, annoying task. Because of this, Python provides the option to use the dotenv
library to better manage environment variables.
The benefit of using the dotenv library is that the process is the same for Windows, macOS, and Linux. The way that this process works is by including a .env
file in the project directory that you’re working in. The file will contain the environment variables that you’re hoping to use in your script.
Let’s see how we can use the dotenv library to manage our environment variables better in Python. First, we’ll need to install the dotenv library, which can be done using either pip
or conda
:
# Install dotenv
pip install python-dotenv
conda install python-dotenv
Once this is done, we need to create the file in the directory. The easiest way to do this is using the terminal:
touch .env
Once this is done, you can open the file, which is really just a text file. From there, you can add all of the environment variables that you want to use. The way that this is done is by placing different variables on new lines and creating the key-value pair by using an equal sign =
:
API_KEY=123abc
user_name=Nik
From there, in your Python script it’s as easy as importing the library and loading the file:
# Loading an Environment Variable File with dotenv
from dotenv import load_dotenv
load_dotenv()
The function will search through the current directory for the .env
file. If it doesn’t find one, then it continues to move up through the directories to try and find the file.
Similarly, you could simply pass in the full path to the file to make your code more explicit:
# Loading an Environment Variable File Explicitly with dotenv
from dotenv import load_dotenv
load_dotenv('/home/datagy/project/.env')
Using dotenv Safely with Source Control Management Tools
Because environment variables can be used to store sensitive information, it’s important to be mindful of not including them when working with SCM tools like Github. In order to work with these safely, you can add them to a .gitignore
file.
In order to make your code more understandable for others, simply add an example .env
file to your repository. This allows readers of your code to understand what environment variables must be set.
Conclusion
In this tutorial, you learned all about environment variables in Python. Environment variables provide the ability to elegantly and securely run your code. They provide the opportunity to streamline your code without repeating and changing your code. Similarly, they prevent having to share secure items such as API Keys.
You learned how to get and set environment variables in Python using the os
library. You also learned how to use the dotenv
library to make managing environment variables much easier in Python.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Use Python to List Files in a Directory (Folder) with os and glob
- Python: Get and Change the Working Directory
- Python: Check if a File or Directory Exists
- Python Delete a File or Directory: A Complete Guide
- Python dotenv Official Documentation
Updated by
Ashirafu Kibalama
on September 17, 2024
Two Methods for Setting Python Environment Variables on Windows 10 (with a step-by-step YouTube Video Guide)
Setting environment variables is essential for any developer working with Python on Windows 10.
Environment variables can help you manage dependencies, configure settings, and streamline your development process.
This blog post will explore two straightforward methods to set Python environment variables on Windows 10.
We’ll provide detailed, step-by-step instructions to guide you through the process.
Additionally, we’ve included a comprehensive YouTube video guide that walks you through each step for those who prefer visual learning.
By the end of this tutorial, you’ll have the knowledge and confidence to set up your Python environment variables efficiently.
How to Set Python Environment Variable in Windows 10: 2 Methods (Step-by-Step Guide with YouTube Video)
Watch my YouTube video for The 2 Methods To Set Python Environment Variable Windows 10.
Method 1) Using a Unquie Variable name:
1) Open System Properties:
Press Win + X and select System,
or right-click on This PC and select Properties.
Click on Advanced System Settings on the left sidebar.
2) Environment Variables:
Remember to click the «Environment Variables» button at the bottom of the System Properties window.
Then, this page appears:
3) Set a New Environment Variable:
In the Environment Variables window, you can add a new variable or modify an existing one.
Click New under the appropriate section (System variables) to set a new Python Environment Variable for your Windows.
Then, this page appears:
Enter the Variable name and Variable value.
For example, to set the PYTHONPATH variable, you might enter PYTHONPATH as the variable name.
4) Set the path to your Python libraries, i.e. (variable name):
First, type «python» in the Windows search bar, right-click on the Python version installed on your PC, and click «open file location.»
Then, this page appears:
Right-click on the Python version and then click open file location as illustrated below:
Then, this page appears:
Then copy the Python libraries path:
Python libraries path example: C:\Users\User\AppData\Local\Programs\Python\Python312
# Python libraries path example:
C:\Users\User\AppData\Local\Programs\Python\Python312
Go back to step 3)
Then paste the Python libraries path you copied, add a semicolon «;» and again paste the path.
Add these:»\Scripts». C:\Users\User\AppData\Local\Programs\Python\Python312\Scripts
Note: Scripts; S must be a Capital letter.
# Python libraries path example:
C:\Users\User\AppData\Local\Programs\Python\Python312;C:\Users\User\AppData\Local\Programs\Python\Python312\Scripts
5) Save Changes:
Then, this page appears:
Access the Python environment variables you have set by double-clicking on the path name, for example, PYTHONPATH. Then, you should see the Python environment variables.
Finally, Click OK to close each window and save your changes.
6) Prove that you have successfully set your Python environment variables:
Enter «python —version» in the command prompt. If it is successful, you will see the Python Version displayed in the command prompt.
Method 2) Editing an Existing Variable path:
1) Open System Properties:
Press Win + X and select System,
or right-click on This PC and select Properties.
Click on Advanced System Settings on the left sidebar.
2) Environment Variables:
Remember to click the «Environment Variables» button at the bottom of the System Properties window.
Then, this page appears:
3) Edit an existing Environment Variable:
In the Environment Variables window, modify an existing one, for example: «Path».
So Click Path under the appropriate section (System variables) and then click «Edit» to set a new Python Environment Variable for your Windows.
Then, this page appears:
4) Set the path to your Python libraries:
First, type «python» in the Windows search bar, right-click on the Python version installed on your PC, and click «open file location.»
Then, this page appears:
Right-click on the Python version and then click open file location as illustrated below:
Then, this page appears:
Then copy the Python libraries path:
Python libraries path example: C:\Users\User\AppData\Local\Programs\Python\Python312
# Python libraries path example:
C:\Users\User\AppData\Local\Programs\Python\Python312
Go back to step 3)
Then click New:
This appears:
After adding the Path:
Then paste the Python libraries path you copied:
C:\Users\User\AppData\Local\Programs\Python\Python312
Again click New and paste the path.
Add these:»\Scripts». C:\Users\User\AppData\Local\Programs\Python\Python312\Scripts
Note: Scripts; S must be a Capital letter.
# Python libraries path example:
C:\Users\User\AppData\Local\Programs\Python\Python312\Scripts
5) Save Changes:
Finally, Click OK to close each window and save your changes.
6) Prove that you have successfully set your Python environment variables:
Enter «python —version» in the command prompt. If it is successful, you will see the Python Version displayed in the command prompt.
Conclusion
Mastering setting environment variables for Python on Windows 10 is crucial in optimizing your development workflow.
This blog post has provided you with clear, actionable steps to set your Python environment variables.
For those who learn best through visual aids, our step-by-step YouTube video guide is an excellent resource to follow along with.
Implementing these methods will better equip you to handle various Python projects, ensuring a smoother and more productive development experience.
If you have any questions or need further assistance, feel free to leave a comment below or contact us. Happy coding!
Other Posts:
1 Best 4 Free Exchange Rate APIs With Python Examples (Step-by-Step with YouTube Video)
2 Build a CV or Resume Generator pdf Flask Python With Source Code (Step-by-Step with YouTube Video)
3 Ckeditor Alternative: How To Upload An Image Ckeditor Flask Alternative/ Summernote Image Upload Flask Python
4 A Beginner’s Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting
5 How to fix: Python was not found Error: Run without arguments to install from the Microsoft Store or disable this shortcut from Settings Manage App Execution Aliases.
6 How to Change or Activate a Virtual Environment in Pycharm Windows/ macOS
Python is a well-known high-level programming language that has been around since 1991.
It is thought to be one of the server-side programming languages with the most flexibility.
Unlike most Linux distributions, Windows does not come with Python installed. However, you can easily install it in just a few steps.
How to get and set environment variables in Python: Python 3 Installation on Windows
It’s not hard to install and setup Python environment variables on your personal computer. It will only take a few easy steps:
Step 1: Download the Python Installer
Option 1: Download using the Microsoft Store
Did you know that the Microsoft Store may also be used to install Python on your computer?
To install Python using Microsoft Store do the following:
- In the start menu, type or search for “Microsoft Store”.
- Once the Microsoft Store is open, search for the word “Python”
The Microsoft Store has several versions of Python. If you are unsure of what you are doing, it is best to use the most recent version.
You can access and choose a different version of Python inside the Store and it is free to download software.
- Click the desired version of Python, then click “Get“, your Windows computer will now have Python installed.
When the installation is done, click the Start button and you should see that Python and IDLE have been added to your list of recently installed programs.
The Microsoft Store package for Python 3.10 is published by the Python Software Foundation and is easy to install. It is mainly intended for interactive use, such as by students.
Warning: If you are asked to pay for Python, you have not selected the correct package.
Option 2: Download using Windows Installer
The installation procedure involves downloading the official Python .exe installer and running it on your system.
- Go to the official Python website and find the Downloads tab for Windows.
- Then choose to download the Windows installer that corresponds to your system type (32-bit or 64-bit).
Step 2: Run the Executable Installer
After downloading the installer, execute the Python installer.
- Make sure to check the “Install launcher for all users” check box. Additionally, you may check the Add Python 3.10 to path check box to include the interpreter in the execution path.
- Select “Customize Installation” to continue.
- By selecting the checkboxes below you will be redirected to the Optional Features:
- Select Next.
- You will see Advanced Options and select the Install for all users and Add Python to environment variables checkboxes.
- Click Install to start the installation.
- After the installation, you’ll see a Python Setup successful
Step 3: Add Python to environmental variables
In setting up Python, you must take this step to use Python from the command line.
If you set the Advanced options and added Python to the environment variables during installation, you can skip this step.
- Search for “Advanced System Settings” in the start menu and select “View Advanced System Settings”.
Inside the “System Properties“, select the “Environmental Variables” button.
- Next is to locate the Python installation directory. If you follow our previous step above, you will locate your Python directory in this location:
C:\Users\Computer_Name\AppData\Local\Programs\Python\Python310
The folder name of the Python location may be different if you installed a different version of Python.
- Add the location of the Python installation directory to the Path Variable.
Step 4: Verify the Python Installation
You have now installed Python 3.10.5 on Windows 10. To verify the installation, you can use the command line or the IDLE app.
- In the start menu, search for the cmd or command prompt.
- Once the Windows Command Prompt is open, type py and you will see this:
- You can also use the IDLE (Python 3.10 64-bit)
- In the start menu, search Python and select the IDLE (Python 3.10 64-bit)
Step 5: Verify Pip Was Installed
Most Python packages should be installed with Pip, especially when working in virtual environments. To verify whether Pip was installed follow the steps below:
- In the Start menu type “cmd“.
- After you have opened the Windows Command Prompt, type
pip -V
into it.
Step 6: Install Virtual Environment (Optional)
In order to create isolated virtual environments for your Python projects, you will need to install virtualenv
.
Why use virtualenv?
By default, Python software packages are installed on the whole system. So, when you change a project-specific package, all of your Python projects are affected.
You would want to avoid this, and the best way to do so is to have virtual environments for each project that are different from the others.
To install virtualenv:
- In the Start menu type “cmd“.
- Once the Windows Command Prompt is open, type the following pip command:
C:\Users\Computer_Name> pip install virtualenv
Summary
In summary, we have learned how to install Python setup environment variables on Windows. Python works with many different operating systems, including Mac OS X and Linux.
Setting up PATH for Python Environment on operating systems offers a list of directories where the OS searches for executables.
Make certain that the Python environment has been correctly installed, setup, and is operating normally.
This is a brief overview of the possibilities for setting environment variables in a virtual environment (venv).
Environment variables can be set inside your Python script. All child processes will inherit the environment variables and their values.
import os os.environ['COMPOSER'] = 'Tchaikovsky'
Set environment variables in activate.bat or activate.ps1
If you want to set environment variables each time the venv is started, you can assign them inside the activation script. If you’re running a PowerShell terminal, you should edit Activate.ps1 in <YOUR_ENV>/Scripts and add an extra line to set an environment variable as follows.
$env:COMPOSER = 'Rachmaninov'
If you’re running a Windows command prompt, edit activate.bat in <YOUR_ENV>/Scripts and add the following line.
set COMPOSER = 'Stravinsky'
The key-value .env file in Visual Studio Code
VS Code automatically searches for an .env file. In this file, you can specify key-value pairs that are loaded as environment variables.
Say thanks, ask questions or give feedback
Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.