This question needs a proper answer:
Just use the standard package site
, which was made for this job!
and here is how (plagiating my own answer to my own question on the very same topic):
- Open a Python prompt and type
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python37\\site-packages'
...
(Alternatively, call python -m site --user-site
for the same effect.)
- Create this folder if it does not exist yet:
...
>>> import os
>>> os.makedirs(site.USER_SITE)
...
(Or, in Bash, your preferred variant of makedirs -p $(python -m site --user-site)
.)
- Create a file
sitecustomize.py
(with exactly this filename, or it won’t work) in this folder containing the content ofFIND_MY_PACKAGES
, either manually or using something like the following code. Of course, you have to changeC:\My_Projects
to the correct path to your custom import location.
...
>>> FIND_MY_PACKAGES = """
import site
site.addsitedir(r'C:\My_Projects')
"""
>>> filename = os.path.join(site.USER_SITE, 'sitecustomize.py')
>>> with open(filename, 'w') as outfile:
... print(FIND_MY_PACKAGES, file=outfile)
And the next time you start Python, C:\My_Projects
is present in your sys.path
, without having to touch system-wide settings. Bonus: the above steps work on Linux, too!
Why does this work?
From the documentation of standard library package site
:
[Then] an attempt is made to import a module named
sitecustomize
, which can perform arbitrary site-specific customizations. […].
So if you create a module named sitecustomize
anywhere in PYTHONPATH, package site will execute it at Python startup. And by calling site.addsitedir
, the sys.path
can be safely extended to your liking.
This question needs a proper answer:
Just use the standard package site
, which was made for this job!
and here is how (plagiating my own answer to my own question on the very same topic):
- Open a Python prompt and type
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python37\\site-packages'
...
(Alternatively, call python -m site --user-site
for the same effect.)
- Create this folder if it does not exist yet:
...
>>> import os
>>> os.makedirs(site.USER_SITE)
...
(Or, in Bash, your preferred variant of makedirs -p $(python -m site --user-site)
.)
- Create a file
sitecustomize.py
(with exactly this filename, or it won’t work) in this folder containing the content ofFIND_MY_PACKAGES
, either manually or using something like the following code. Of course, you have to changeC:\My_Projects
to the correct path to your custom import location.
...
>>> FIND_MY_PACKAGES = """
import site
site.addsitedir(r'C:\My_Projects')
"""
>>> filename = os.path.join(site.USER_SITE, 'sitecustomize.py')
>>> with open(filename, 'w') as outfile:
... print(FIND_MY_PACKAGES, file=outfile)
And the next time you start Python, C:\My_Projects
is present in your sys.path
, without having to touch system-wide settings. Bonus: the above steps work on Linux, too!
Why does this work?
From the documentation of standard library package site
:
[Then] an attempt is made to import a module named
sitecustomize
, which can perform arbitrary site-specific customizations. […].
So if you create a module named sitecustomize
anywhere in PYTHONPATH, package site will execute it at Python startup. And by calling site.addsitedir
, the sys.path
can be safely extended to your liking.
You may need to add Python to PATH
if you’ve installed Python, but typing python
on the command line doesn’t seem to work. You may be getting a message saying that the term python
isn’t recognized, or you may end up with the wrong version of Python running.
A common fix for these problems is adding Python to the PATH
environment variable. In this tutorial, you’ll learn how to add Python to PATH
. You’ll also learn about what PATH
is and why PATH
is vital for programs like the command line to be able to find your Python installation.
The steps that you’ll need to take to add something to PATH
will depend significantly on your operating system (OS), so be sure to skip to the relevant section if you’re only interested in this procedure for one OS.
Note that you can use the following steps to add any program to PATH
, not just Python.
How to Add Python to PATH
on Windows
The first step is to locate the directory in which your target Python executable lives. The path to the directory is what you’ll be adding to the PATH
environment variable.
To find the Python executable, you’ll need to look for a file called python.exe
. The Python executable could be in a directory in C:\Python\
or in your AppData\
folder, for instance. If the executable were in AppData\
, then the path would typically look something like this:
C:\Users\<USER>\AppData\Local\Programs\Python
In your case, the <USER>
part would be replaced by your currently logged-in user name.
Once you’ve found the executable, make sure it works by double-clicking it and verifying that it starts up a Python REPL in a new window.
If you’re struggling to find the right executable, you can use Windows Explorer’s search feature. The issue with the built-in search is that it’s painfully slow. To perform a super-fast full system search for any file, a great alternative is Everything:
Those paths highlighted in yellow, namely those at \WindowsApps
and \Python310
, would be ideal candidates to add to PATH
because they look like executables at the root level of an installation. Those highlighted in red wouldn’t be suitable because some are part of a virtual environment—you can see venv
in the path—and some are shortcuts or internal Windows installations.
You may also encounter Python executables that are installed within the folder for a different program. This is due to the fact that many applications bundle their own version of Python within them. These bundled Python installations would also be unsuitable.
Once you’ve located your Python executable, open the Start menu and search for the Edit the system environment variables entry, which opens up a System Properties window. In the Advanced tab, click on the button Environment Variables. There you’ll see User and System variables, which you’ll be able to edit:
In the section entitled User Variables, double-click on the entry that says Path. Another window will pop up showing a list of paths. Click the New button and paste the path to your Python executable there. Once that’s inserted, select your newly added path and click the Move Up button until it’s at the top.
That’s it! You may need to reboot your computer for the changes to take effect, but you should now be able to call python
from the command line.
For setting the PATH
environment variable from the command line, check out the section on Configuring Environment Variables in the Windows Python coding setup guide. You can also find instructions in the supplemental materials:
You may also want to set up PATH
on your Linux or macOS machine, or perhaps you’re using Windows Subsystem for Linux (WSL). If so, read the next section for the procedure on UNIX-based systems.
How to Add Python to PATH
on Linux and macOS
Since Python typically comes pre-installed on UNIX-based systems, the most common problem on Linux and macOS is for the wrong python
to run, rather than not finding any python
. That said, in this section, you’ll be troubleshooting not being able to run python
at all.
The first step is locating your target Python executable. It should be a program that you can run by first navigating to the containing directory and then typing ./python
on the command line.
You need to prepend the call to the Python executable with its relative path in the current folder (./
) because otherwise you’ll invoke whichever Python is currently recorded on your PATH
. As you learned earlier, this might not be the Python interpreter that you want to run.
Often the Python executable can be found in the /bin/
folder. But if Python is already in the /bin/
folder, then it’s most likely already on PATH
because /bin/
is automatically added by the system. If this is the case, then you may want to skip to the section on the order of paths within PATH
.
Since you’re probably here because you’ve installed Python but it’s still not being found when you type python
on the command line, though, you’ll want to search for it in another location.
That said, it might be that /bin/
has been removed from PATH
altogether, in which case you might skip forward to the section on mangaging PATH
.
Once you’ve located your Python executable and are sure it’s working, take note of the path for later. Now it’s time to start the process of adding it to your PATH
environment variable.
First, you’ll want to navigate to your home folder to check out what configuration scripts you have available:
You should see a bunch of configuration files that begin with a period (.
). These are colloquially known as dotfiles and are hidden from ls
by default.
One or two dotfiles get executed whenever you log in to your system, another one or two run whenever you start a new command-line session, and most others are used by other applications for configuration settings.
You’re looking for the files that run when you start your system or a new command-line session. They’ll probably have names similar to these:
.profile
.bash_profile
.bash_login
.zprofile
.zlogin
The keywords to look for are profile and login. You should, in theory, only have one of these, but if you have more than one, you may need to read the comments in them to figure out which ones run on login. For example, .profile
file on Ubuntu will typically have the following comment:
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
So, if you have .profile
but also .bash_profile
, then you’ll want to use .bash_profile
.
You can also use a .bashrc
or .zshrc
file, which are scripts that run whenever you start a new command-line session. Run command (rc) files are common places to put PATH
configurations.
To add the Python path to the beginning of your PATH
environment variable, you’re going to be executing a single command on the command line.
Use the following line, replacing <PATH_TO_PYTHON>
with your actual path to the Python executable, and replace .profile
with the login script for your system:
$ echo export PATH="<PATH_TO_PYTHON>:$PATH" >> ~/.profile
This command adds export PATH="<PATH_TO_PYTHON>:$PATH"
to the end of .profile
. The command export PATH="<PATH_TO_PYTHON>:$PATH"
prepends <PATH_TO_PYTHON>
to the PATH
environment variable. It’s similar to the following operation in Python:
>>>
>>> PATH = "/home/realpython/apps:/bin"
>>> PATH = f"/home/realpython/python:{PATH}"
>>> PATH
'/home/realpython/python:/home/realpython/apps:/bin'
Since PATH
is just a string separated by colons, prepending a value involves creating a string with the new path, a colon, then the old path. With this string, you set the new value of PATH
.
To refresh your current command-line session, you can run the following command, replacing .profile
with whichever login script you’ve chosen:
Now, you should be able to call python
from the command line directly. The next time you log in, Python should automatically be added to PATH
.
If you’re thinking this process seems a bit opaque, you’re not alone! Read on for more of a deep dive into what’s going on.
Understanding What PATH
Is
PATH
is an environment variable that contains a list of paths to folders. Each path in PATH
is separated by a colon or a semicolon—a colon for UNIX-based systems and a semicolon for Windows. It’s like a Python variable with a long string as its value. The difference is that PATH
is a variable accessible by almost all programs.
Programs like the command line use the PATH
environment variable to find executables. For example, whenever you type the name of a program into the command line, the command line will search various places for the program. One of the places that the command line searches is PATH
.
All the paths in PATH
need to be directories—they shouldn’t be files or executables directly. Programs that use PATH
take each directory in turn and search all the files within it. Subdirectories within directories in PATH
don’t get searched, though. So it’s no good just adding your root path to PATH
!
It’s also important to note that programs that use PATH
typically don’t search for anything except executables. So, you can’t use PATH
as a way to define shortcuts to commonly used files.
Understanding the Importance of Order Within PATH
If you type python
into the command line, the command line will look in each folder in the PATH
environment variable for a python
executable. Once it finds one, it’ll stop searching. This is why you prepend the path to your Python executable to PATH
. Having the newly added path first ensures that your system will find this Python executable.
A common issue is having a failed Python installation on your PATH
. If the corrupted executable is the first one that the command line comes across, then the command line will try and run that and then abort any further searching. The quick fix for this is just adding your new Python directory before the old Python directory, though you’d probably want to clean your system of the bad Python installation too.
Reordering PATH
on Windows is relatively straightforward. You open the GUI control panel and adjust the order using the Move Up and Move Down buttons. If you’re on a UNIX-based operating system, however, the process is more involved. Read on to learn more.
Managing Your PATH
on UNIX-based Systems
Usually, your first task when managing your PATH
is to see what’s in there. To see the value of any environment variable in Linux or macOS, you can use the echo
command:
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/home/realpython/badpython:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
Note that the $
symbol is used to tell the command line that the following identifier is a variable. The issue with this command is that it just dumps all the paths on one line, separated by colons. So you might want to take advantage of the tr
command to translate colons into newlines:
$ echo $PATH | tr ":" "\n"
/usr/local/sbin
/usr/local/bin
/usr/sbin
/home/realpython/badpython
/usr/bin
/sbin
/bin
/usr/games
/usr/local/games
In this example, you can see that badpython
is present in PATH
. The ideal course of action would be to perform some PATH
archaeology and figure out where it gets added to PATH
, but for now, you just want to remove it by adding something to your login script .
Since PATH
is a shell string, you don’t have access to convenient methods to remove parts of it, like you would if it were a Python list. That said, you can pipe together a few shell commands to achieve something similar:
export PATH=`echo $PATH | tr ":" "\n" | grep -v 'badpython' | tr "\n" ":"`
This command takes the list from the previous command and feeds it into grep
, which, together with the -v
switch, will filter out any lines containing the substring badpython
. Then you can translate the newlines back to colons, and you have a new and valid PATH
string that you use right away to replace your old PATH
string.
Though this can be a handy command, the ideal solution would be to figure out where that bad path gets added. You could try looking at other login scripts or examine specific files in /etc/
. In Ubuntu, for instance, there’s a file called environment
, which typically defines a starting path for the system. In macOS, that might be /etc/paths
. There can also be profile
files and folders in /etc/
that might contain startup scripts.
The main difference between configurations in /etc/
and in your home folder is that what’s in /etc/
is system-wide, while whatever’s in your home folder will be scoped to your user.
It can often involve a bit of archeology to track down where something gets added to your PATH
, though. So, you may want to add a line in your login or rc script that filters out certain entries from PATH
as a quick fix.
Conclusion
In this tutorial, you’ve learned how to add Python, or any other program, to your PATH
environment variable on Windows, Linux, and macOS. You also learned a bit more about what PATH
is and why its internal order is vital to consider. Finally, you also discovered how you might manage your PATH
on a UNIX-based system, seeing as it’s more complex than managing your PATH
on Windows.
If you are a beginner, then this article is for you. As a beginner, you might face problems in setting a proper path for python. In today’s tutorial, we will learn how to set a default path for python whenever we install python into our system.
Introduction
Unlike most operating systems such as Unix, Windows does not include a system-supported installation of Python. To run Python conveniently from a command prompt, you might consider changing some default environment variables in Windows. To temporarily set environment variables, open Command Prompt and use the set command:
C:\>set PATH=C:\Program Files\Python 3.6; %PATH%
Why to set up a path for python?
If you’ve installed Python in Windows using the default installation options, then the path to Python will not be added to the Windows Path variable. The Path variable lists the directories that will be searched for executing when you type a command in the command prompt. By adding the path to the Python executable, you will be able to access python.exe just by typing the python keyword in your command prompt. You will not need to specify the full path to the program.
Let us see what happens if we enter the python command in the command prompt and the path to that executable is not added to the Path variable:
C:\>python 'python' is not recognized as an internal or external command, operable program or batch file.
As you can see from the above output, the command was not found. Therefore, to run python.exe, you will need to specify the full path to the executable.
How to select default path while installing python?
There is an easy way to set up the default path during installing the Python. Every python installer comes with an option to add a python path into environmental variables. This will ensure that you can run python from your terminal. To do this –
- Get Python Installer from python.org.
- Get the installer and an installation window will appear.
- Press the “Add Python X.X to your PATH” option and install the python.
This way you can set up a default path without any headache. If you already have python installed and do not want to reinstall it, then move on to the next methods.
To permanently modify the default environment variables : My Computer > Properties > Advanced System Settings > Environment Variables > Edit
Steps to follow in detail.
- Right-click on ‘My Computer’ or ‘This PC.’ :-To navigate to the Windows Environment Variables screen, where you can add/edit your paths, right-click on the ‘This PC‘ icon. Then, select ‘Properties.’
- Select ‘Properties’ at the bottom of the Context Menu.: – After selecting the properties, the settings pop up.
- Next, select ‘Advanced system settings.’
- Check ‘Environment Variables...’ in the Advanced Tab.: After pressing on the advance settings, another window comes up which shows the Environment Variable option.
- Under ‘System Variables, ‘ Check on the New button in the top half of the dialog to make a new user variable.
- A new user dialog box pop ups which contain Variable name and variable value.
Before you type any values, you’ll need to locate the relevant Python paths. The paths that you’ll need to get are:
- copy the python path as show in the image below
Now let’s fill the New User Variable box that you saw earlier:
For the Variable name, type ‘Path.‘ For the Variable value, copy the full Python application path, then use a semicolon.
Now select OK
Using python from Command Prompt
- Press on the start menu.
- Type Command Prompt and open it
- Type “python.”
- A response from the python interpreter comes, i.e., it will show the python version currently installed in your system else.
- You will get an error message that will be written as “python is not recognized as an internal or external command.” This means that there is something wrong with the path variable setting.
Checking of python path
- Press on the start menu.
- Type Command Prompt and open it
- Type “python.”
- Now type the following code.
import os os.environ['PYTHONPATH']
OUTPUT:- 'C:\Program Files\Python 3.6'
How to handle multiple paths in python?
You may have two versions of python installed in windows in your system, let’s say 2.7 and 3.9. You want to run one of your projects in the python 2.7 version and another project in the 3.9 version. So the problem that lands up here is how you can specify which version you want to use for a specific python project?
So, to check all the versions of python installed in your windows environment , just type
py -0p in command prompt
So, today I will show you 2 methods of how to manage multiple python paths in windows?
Method 1: By defining the path of the versions
Whenever you try to run Python in the command prompt, it searches the %PATH% environment variable and checks for an executable file which can either be a batch file (.bat), command file (.exe), or any other executable file (.exe) that matches the name given. Once the correct file is found, it executes the program using that file. Now, if you have two versions of Python installed on your system (Python 2.7 and 3.9), then the path variable will contain the location of both the directories. But, there is a problem. The problem is once Windows finds the first match, it will stop examining any other path.
To overcome this problem, you have to call one or both applications using their path explicitly. For example, as you can see below, I have two versions of Python installed on my system.
- To execute python 2.7 you must call C:\Python27\python.exe
- To execute python 3.9 we had to type python3.9.exe
This method is one of the simplest method for managing multiple paths of python.
Method 2: Creating a shortcut
If you want to avoid using the entire path, create a shortcut for each python.exe file and rename it as python27 and python39.
In order to create the shortcuts, follow the given steps:
- Navigate to the folder containing the Python version you want to create a shortcut for.
- Right-click and create a shortcut.
- Rename the shortcut.
To run a file in python 2.7
Also, Check Out Editors Choice:
Conclusion
I hope this article helps you in setting a proper path for python in Windows operating system. As a beginner, you might face difficulties, but no worries, keep reading our tutorials on python and being a pro. Drop a comment if you have doubts. We are just one reply away. Till then, keep reading.
Happy Pythoning Geeks!!
There are few ways to add Python to Windows PATH. In this guide, you’ll see two methods to add Python to Windows path:
- Via the installation of a recent version of Python
- Manual entry of the paths
Method 1: Install a Recent Version of Python
You can easily add Python to Windows path by downloading a recent version of Python, and then checking the box to Add Python to PATH at the bottom of the setup screen:
Add Python to PATH
Finish the installation, and you should be good to go.
Alternatively, you may manually add the paths into the Environment variables.
Method 2: Manually add Python to Windows Path
If you wish to stick with the previous version of Python, you may apply the steps below to manually add Python to Windows path.
First, navigate to the Windows Environment Variables screen (where you can add/edit your paths):
- Press the Windows Key + R on your keyboard in order to open the Run dialog box
- Type sysdm.cpl to open the System Properties
- Go to the Advanced tab and then click on the ‘Environment Variables…‘
That should take you to the Environment Variables screen, where you can add/edit your paths.
Under the User variables box, click on ‘New…‘ to add the ‘Path’ variable (note that if your ‘Path’ variable already exists, then click on ‘Edit…’ instead):
User variables
OneDrive
TEMP
TMP
New… Edit…
You should then see the New User Variable box, where you may add/edit variables:
Variable name:
Variable value:
Before you type any values, you’ll need to locate the relevant Python paths. The paths that you’ll need to get are:
(1) The Python application path, which is the folder where you originally installed Python. You can find the Python application path by following these steps:
- Type “Python” in the Windows Search Bar
- Right-click on the Python App, and then select “Open file location“
- Right-click again on the Python shortcut, and then select “Open file location“
Here is an example of a Python application path:
C:\Users\Ron\AppData\Local\Programs\Python\Python39
(2) The Python Scripts path. The Scripts folder should be located within the Python application path. Example:
C:\Users\Ron\AppData\Local\Programs\Python\Python39\scripts
After you obtained the paths, fill the New User Variable box that you saw earlier:
- For the Variable name, type ‘Path‘
- For the Variable value, paste the full Python application path, then add semicolon (as highlighted in yellow below), and finally paste the Python Scripts path.
For our example:
Variable name: Path
Variable value: C:\Users\Ron\AppData\Local\Programs\Python\Python39;C:\Users\Ron\AppData\Local\Programs\Python\Python39\Scripts
Press ‘OK’ and you would then see your new Python Path under the ‘User variables‘ section. Don’t forget to press ‘OK‘ again so that the changes will get implemented.
User variables
OneDrive
Path C:\Users\Ron\AppData\Local\Programs\Python\Python39;C:\Users\…
TEMP
TMP
New… Edit…
System variables
…
…
…
OK Cancel
You just added Python to the Windows Path.
You should be able to install Python packages easily, by opening the Windows Command Prompt and then typing:
pip install package_name
For example, to install the Pandas package, simply type ‘pip install pandas‘ and then press ENTER:
pip install pandas
Similarly, you may upgrade PIP by typing the following command:
python -m pip install --upgrade pip