Директория python в windows 10

Иногда нам нужно проверить пакеты или модули в том месте, где установлен Python. В этой статье мы покажем три способа, как найти папку в которой установлен Python в Windows:

  • с помощью командной строки
  • через меню “Пуск
  • используя параметры переменной среды

Итак, давайте начнем!

Примечание редакции: о собственно установке Python читайте в статье “Как установить Python на Windows 10 или 11”.

Чтобы узнать, где установлен Python, используя командную строку Windows, следуйте приведенным ниже примерам.

Пример 1: команда where

Для начала попробуйте использовать команду where, чтобы вывести путь к директории установленного Python:

>where python

Как видите, в результате нужный путь был найден и отображен в командной строке:

Использование where  в командной строке. На следующей строке после введенной команды выведен путь, по которому  в Windows установлен Python

Пример 2: команда py

Команда py с опцией --list-paths также может быть использована для перечисления путей к Python:

Использование команды py --list-paths в командной строке

Как найти место установки Python в Windows с помощью меню “Пуск”

Чтобы найти, где установлен Python, используя меню “Пуск”, выполните следующую процедуру.

Сначала найдите файл “Python.exe” в меню “Пуск”. Затем выберите опцию “Открыть расположение файла”, чтобы открыть соответствующую папку:

Опция "Open file location" в меню "Пуск".

В результате вы будете перемещены в каталог, где установлен Python:

Каталог, где установлен Python

Как найти место установки Python в Windows с помощью переменной окружения

Чтобы узнать, где установлен Python, используя переменную окружения PATH, выполните следующие действия.

Шаг 1. Откройте расширенные системные настройки

Нажмите Window+I, чтобы открыть Настройки системы. Затем выберите “Система” из списка доступных категорий:

Окно настроек

Найдите в строке поиска “Дополнительные параметры системы” и откройте их:

Дополнительные параметры системы

Шаг 2. Откройте переменные среды

В Дополнительных параметрах системы нажмите на кнопку “Переменные среды”:

Переменные среды

Шаг 3. Откройте переменную среды Path

На вкладке “Системные переменные” выберите “Path” и нажмите кнопку “Изменить” для просмотра сведений о пути:

Вкладка "Системные переменные"

Из переменной среды Path можно найти место, где установлен Python, как показано ниже:

Окно редактирования переменной окружения с выделенным путем к Python

Заключение

Узнать, где в Windows установлен Python, можно разными способами, например, с помощью командной строки, меню “Пуск” и системных переменных среды.

Для первого способа откройте командную строку и воспользуйтесь командой where python. Во втором случае найдите “python.exe” в меню “Пуск” и откройте местоположение файла. При третьем подходе вы можете узнать расположение Python через переменную среды “Path”.

Перевод статьи Rafia Zafar «How Can I Find Where Python is Installed on Windows».

I want to find out my Python installation path on Windows. For example:

C:\Python25

How can I find where Python is installed?

Stevoisiak's user avatar

Stevoisiak

24.1k28 gold badges122 silver badges226 bronze badges

asked Mar 15, 2009 at 9:09

Fang-Pen Lin's user avatar

Fang-Pen LinFang-Pen Lin

13.5k15 gold badges67 silver badges96 bronze badges

1

In your Python interpreter, type the following commands:

>>> import os
>>> import sys
>>> os.path.dirname(sys.executable)
'C:\\Python25'

Also, you can club all these and use a single line command. Open cmd and enter following command

python -c "import os, sys; print(os.path.dirname(sys.executable))"

Mrityunjai's user avatar

answered Mar 15, 2009 at 13:17

elo80ka's user avatar

13

If you have Python in your environment variable then you can use the following command in cmd or powershell:

 where python

or for Unix enviroment

 which python

command line image :

enter image description here

answered Apr 17, 2017 at 16:04

Aekansh Kansal's user avatar

Aekansh KansalAekansh Kansal

2,8291 gold badge15 silver badges17 bronze badges

3

It would be either of

  • C:\Python36
  • C:\Users\(Your logged in User)\AppData\Local\Programs\Python\Python36

answered Aug 18, 2017 at 9:52

Amol Manthalkar's user avatar

Amol ManthalkarAmol Manthalkar

1,9202 gold badges16 silver badges16 bronze badges

5

If you need to know the installed path under Windows without starting the python interpreter, have a look in the Windows registry.

Each installed Python version will have a registry key in either:

  • HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
  • HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath

In 64-bit Windows, it will be under the Wow6432Node key:

  • HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath

yincrash's user avatar

yincrash

6,3941 gold badge40 silver badges41 bronze badges

answered Mar 15, 2009 at 21:08

codeape's user avatar

codeapecodeape

98.1k24 gold badges159 silver badges190 bronze badges

8

Simple way is

  1. open CMD
  2. type where python in cmd

Sorry for my bad English's user avatar

answered Jan 30, 2020 at 14:13

BigData-Guru's user avatar

BigData-GuruBigData-Guru

1,1711 gold badge15 silver badges20 bronze badges

2

If you have the py command installed, which you likely do, then just use the --list-paths/-0p argument to the command:

py --list-paths

Example output:

Installed Pythons found by py Launcher for Windows
-3.8-32 C:\Users\cscott\AppData\Local\Programs\Python\Python38-32\python.exe *
-2.7-64 C:\Python27\python.exe

The * indicates the currently active version for scripts executed using the py command.

answered Dec 9, 2019 at 20:48

carlin.scott's user avatar

carlin.scottcarlin.scott

6,2943 gold badges31 silver badges35 bronze badges

1

On my windows installation, I get these results:

>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> sys.platform
'win32'
>>>

(You can also look in sys.path for reasonable locations.)

answered Mar 15, 2009 at 10:18

gimel's user avatar

gimelgimel

83.6k10 gold badges77 silver badges105 bronze badges

2

Its generally

‘C:\Users\user-name\AppData\Local\Programs\Python\Python-version’

or
try using (in cmd )

where python

answered Apr 12, 2020 at 18:45

utkarsh2299's user avatar

In the sys package, you can find a lot of useful information about your installation:

import sys
print sys.executable
print sys.exec_prefix

I’m not sure what this will give on your Windows system, but on my Mac executable points to the Python binary and exec_prefix to the installation root.

You could also try this for inspecting your sys module:

import sys
for k,v in sys.__dict__.items():
    if not callable(v):
        print "%20s: %s" % (k,repr(v))

answered Mar 15, 2009 at 9:41

Guðmundur H's user avatar

Guðmundur HGuðmundur H

11.5k3 gold badges24 silver badges22 bronze badges

2

If You want the Path After successful installation then first open you CMD and type
python or python -i

It Will Open interactive shell for You and Then type

import sys

sys.executable

Hit enter and you will get path where your python is installed …

Community's user avatar

answered Oct 18, 2018 at 7:30

Rutvik Vijaybhai Bhimani's user avatar

1

To know where Python is installed you can execute where python in your cmd.exe.

anothernode's user avatar

anothernode

5,16113 gold badges45 silver badges63 bronze badges

answered Jul 27, 2018 at 6:21

4

You can search for the «environmental variable for you account». If you have added the Python in the path, it’ll show as «path» in your environmental variable account.

but almost always you will find it in
«C:\Users\%User_name%\AppData\Local\Programs\Python\Python_version»

the ‘AppData‘ folder may be hidden, make it visible from the view section of toolbar.

answered Sep 14, 2018 at 9:19

Amit Gupta's user avatar

Amit GuptaAmit Gupta

2,7084 gold badges24 silver badges37 bronze badges

Make use of the Python Launcher for Windows (available as of 3.3). It is compatible with all available versions of python.

First, check if the launcher is available:

py 

starts the latest installed version of Python

To see all Python versions available on your system and their path:

py -0p

or

py --list-paths

For a specific Python version path—especially useful with multiple python installations:

py -3.7 -c "import os, sys; print(os.path.dirname(sys.executable))"

python 2

py -2 -c "import os, sys; print(os.path.dirname(sys.executable))"

py installed location is C:\Windows\py.exe if installed for all users, otherwise can be found at C:\Users\username\AppData\Local\Programs\Python\Launcher.
It does not require the environment PATH variable to be set if installed for all users.

answered Apr 25, 2022 at 2:23

oyeyipo's user avatar

oyeyipooyeyipo

3693 silver badges11 bronze badges

You can find it in the Windows GUI, but you need to select “show hidden” in the menu. Directory where python is installed on my Win10 computer:

C:\Users\username\AppData\Local\Programs\Python\Python310

Very handy if you use python pip to install packages.

Suraj Rao's user avatar

Suraj Rao

29.4k11 gold badges94 silver badges103 bronze badges

answered Dec 31, 2021 at 14:35

Wingrider07's user avatar

1

If anyone needs to do this in C# I’m using the following code:

static string GetPythonExecutablePath(int major = 3)
{
    var software = "SOFTWARE";
    var key = Registry.CurrentUser.OpenSubKey(software);
    if (key == null)
        key = Registry.LocalMachine.OpenSubKey(software);
    if (key == null)
        return null;

    var pythonCoreKey = key.OpenSubKey(@"Python\PythonCore");
    if (pythonCoreKey == null)
        pythonCoreKey = key.OpenSubKey(@"Wow6432Node\Python\PythonCore");
    if (pythonCoreKey == null)
        return null;

    var pythonVersionRegex = new Regex("^" + major + @"\.(\d+)-(\d+)$");
    var targetVersion = pythonCoreKey.GetSubKeyNames().
                                        Select(n => pythonVersionRegex.Match(n)).
                                        Where(m => m.Success).
                                        OrderByDescending(m => int.Parse(m.Groups[1].Value)).
                                        ThenByDescending(m => int.Parse(m.Groups[2].Value)).
                                        Select(m => m.Groups[0].Value).First();

    var installPathKey = pythonCoreKey.OpenSubKey(targetVersion + @"\InstallPath");
    if (installPathKey == null)
        return null;

    return (string)installPathKey.GetValue("ExecutablePath");
}

answered Apr 5, 2017 at 11:10

Peter's user avatar

PeterPeter

37.1k39 gold badges142 silver badges199 bronze badges

2

This worked for me: C:\Users\Your_user_name\AppData\Local\Programs\Python

My currently installed python version is 3.7.0

Hope this helps!

David's user avatar

David

1,1925 gold badges13 silver badges31 bronze badges

answered Jul 16, 2018 at 6:55

Prashant Gonga's user avatar

Go to C:\Users\USER\AppData\Local\Programs\Python\Python36
if it is not there then
open console by windows+^R
Then type cmd and hit enter
type python if installed in your local file it will show you its version from there type the following
import os
import sys
os.path.dirname(sys.executable)

answered Mar 1, 2019 at 11:34

SATYAJIT MAITRA's user avatar

You could have many versions of Python installed on your machine. So if you’re in Windows at a command prompt, entering something like this…

py --version

…should tell you what version you’re using at the moment. (Maybe replace py with python or python3 if py doesn’t work). Anyway you’d see something like

Python 3.10.2

If you then create a virtual environment using something like this…

py -m venv venv

…that environment will also use that Python version. To verify, activate the environment…

venv\scripts\activate.bat 

You’ll see the name of the command prompt. Now if execute:

where python

…it will show you which Python executable that virtual environment uses. It will be a copy of Python.exe what’s actually in the Scripts subfolder of the virtual environment folder. Of course to see which version that is, again use py --version.

answered Jan 26, 2022 at 15:55

Alan Simpson's user avatar

if you still stuck or you get this

C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36

simply do this replace 2 \ with one

C:\Users\akshay\AppData\Local\Programs\Python\Python36

Kos's user avatar

Kos

4,9209 gold badges38 silver badges42 bronze badges

answered Jun 2, 2018 at 16:48

Ashwarya sharma's user avatar

I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn’t select setting the path when you installed Python 3 that probably won’t work — unless you manually updated the path when you installed it.
In my case it was at c:\Program Files\Python37\python.exe

answered Feb 3, 2019 at 16:39

Douglas Gilliland's user avatar

If you use anaconda navigator on windows, you can go too enviornments and scroll over the enviornments, the root enviorment will indicate where it is installed. It can help if you want to use this enviorment when you need to connect this to other applications, where you want to integrate some python code.

answered Jun 6, 2019 at 10:01

PV8's user avatar

PV8PV8

5,8627 gold badges43 silver badges88 bronze badges

Option 1 : Check System Environment Variables > Path

Option 2 : C:\Users\Asus\AppData\Local\Programs\Python (By default Path)

answered Oct 1, 2022 at 10:09

Jigyanshu Chouhan's user avatar

On my Windows 11, I have two Python installed: 3.11.2 and 3.8. The below commends give only one of them.

Which python

which py

To find out the location of both the below Powershell commands come in handy:

$User = New-Object System.Security.Principal.NTAccount($env:UserName)

$sid = $User.Translate([System.Security.Principal.SecurityIdentifier]).value

New-PSDrive HKU Registry HKEY_USERS

Get-ChildItem "HKU:\${sid}\Software\Python\PythonCore\*\InstallPath"

answered Mar 27 at 23:26

Harry Zhang's user avatar

Python is a versatile and widely used programming language, known for its simplicity and easy-to-understand syntax. When you’re setting up a Python development environment, one of the first tasks is locating where Python is installed on your machine. This information is crucial for configuring different tools and managing libraries and environments.

Python is normally installed in the system’s default program files directory. On Windows, it’s typically found in the “C:\PythonXX” folder. On Linux or Mac, it’s often in “/usr/local/bin/pythonX.X”. You can check your Python installation path by running “python –version” or “which python” in the command line.

Where is Python Installed

This article will help you understand how to find the Python installation location on your system, focusing on different methods and operating systems. This knowledge will assist you in setting up your programming environment correctly and provide a better understanding of how Python interacts with your machine.

Let’s get into it!

Python Installation Locations

On various operating systems like Windows, macOS, or Linux, Python’s installation location can vary due to user preferences or installation packages from different sources.

Python Installation Locations

In this section, we’ll look at the installation location of Python for different operating systems. Specifically, we’ll look at the following:

  1. Python Installation location on Windows
  2. Python Installation location on MacOS
  3. Python Installation location on Linux

1. Python Installation Location on Windows

By default, Python installations on Windows are located in the C:\ directory or C:\Users\<User>\AppData\Local\Programs.

The common installation paths for both 32-bit and 64-bit versions may reside in the C:\PythonXX folder, where XX stands for the Python version (e.g., C:\Python27 for Python 2.7).

In newer installations, the 64-bit version is often located in the C:\Program Files\PythonXX folder, while the 32-bit version is in the C:\Program Files (x86)\PythonXX folder.

To find the exact location of your Python installation on Windows, you can use the command prompt by typing where python and press Enter. This command will display the file paths of any installed Python versions on your system.

The following image demonstrates this prompt:

Finding Python Location with CMD Prompt

2. Python Installation Location on MacOS

On macOS, Python is typically installed in the /Library/Frameworks/Python.framework/Versions directory, with different versions contained in their respective subfolders (e.g., /Library/Frameworks/Python.framework/Versions/3.9 for Python 3.9).

Alternatively, Python installations managed by Homebrew are located in /usr/local/Cellar/python.

To check the exact path of your Python installation, you can open the terminal and type which python or which python3. Pressing “Enter” will display the file path of the active Python version on your system.

3. Python Installation Location on Linux

In most Linux distributions, Python is installed by default and can be found in the /usr/bin/ directory. The installed versions usually include both Python 2 and Python 3.

For Python 2.x, the executable is named python, while for Python 3.x, it’s named python3.

For systems with multiple Python installations or custom installation paths, you can find the location by typing which python or which python3 in the terminal and pressing Enter.

The command will show the file path of the active Python version on your system.

In the next section, we’ll go over how you can use built-in Python modules to locate the Python folder in your system.

How to Use Python’s os and sys Modules to Locate Python Folder

Python’s os and sys modules are built-in modules that allow you to interact with the operating system.

How to Use Python's os and sys Modules to Locate Python Folder

To locate where Python is installed, follow the steps given below:

  1. Run Python interpreter by typing python in the terminal or command prompt.
  2. Execute the following commands:
import os
import sys
print(os.path.dirname(sys.executable))

This Python script is used to print the directory of the Python interpreter being used to execute the script. os.path.dirname(sys.executable) gets the path of the currently running Python interpreter.

The output is given below:

Using Python's os and sys Modules to Locate Python Folder

How to Check the Location of Python Executables

When you are working in Python, you’ll want to install libraries from time to time. In most cases, you might want to check the path of a certain library.

You can check the path of a Python library or executable with the pip package manager. To do this, open up CMD and run the following code:

pip show <package name>

Let’s say I want to check the location of NumPy library on my operating system. To do this, I’ll type the following prompt in CMD:

pip show numpy

The output is given below:

Check the Location of Python Executables with numpy

How to Configure Python Path

When you first install Python on Windows, it’s important that you configure the path environment variable.

This means you should let your operating system know the path of your installation folder, which will allow the interpreter to refer to this path when running Python files.

How to Configure Python Path

We’ve listed a step-by-step guide to setting your environment variable and variables below:

Windows

  1. Right-click on ‘My Computer’ or ‘This PC,’ and select ‘Properties.’
  2. Click on ‘Advanced system settings.’
  3. Go to the ‘Advanced’ tab and click on ‘Environment Variables.’
  4. In the ‘System variables’ section, locate the ‘Path’ variable, select it, and click on ‘Edit.’
  5. Add the path to the Python executable (e.g., C:\Python<version>\Scripts;C:\Python<version>), and click ‘OK.’

macOS and Linux

  1. Open the terminal (Terminal on macOS, and Ctrl + Alt + T on Linux).
  2. Edit the shell configuration file (~/.bashrc for bash shell, ~/.zshrc for zsh shell).
  3. Add the following line: export PATH=”/path/to/python-<version>/bin:$PATH”
  4. Save the file and restart the terminal for the changes to take effect.

How to Verify Python Version and Installation

Before starting any Python project, it’s essential to know the version of Python installed on the system as well as its location.

It’ll help you ensure compatibility between packages, libraries, and other tools.

How to Verify Python Version and Installation

This section will guide you through verifying your Python version and installation using various Python-related commands and performing cross-platform checks.

1. Python-related Commands

To find the version of Python installed on any platform, you can use the python –version command in the terminal or command prompt.

It returns the Python 2 version installed on your system. To check for the Python 3 version, you can use the python3 –version command instead. These commands help you determine which Python interpreter you are currently using.

In case you are using both Python 2 and Python 3 versions, you can verify the compatibility of a specific module by importing it into the Python interpreter.

For example, to check if the re module is compatible, you can try running the following command:

import re
print(re.__version__)

When you run the above command, you’ll get an output similar to the following:

Verifying Python and Package Compatibility

An output like the above suggests that Python’s re module is compatible with your current Python version.

If you’d like to learn how to switch to the latest version of Python, check out our quick and easy guide on how to update Python.

2. Cross-platform Verification

To find where Python is installed on your system, you can use the following Python code snippet for a cross-platform solution:

import sys
print(sys.executable)

This code will print the location of the Python interpreter executable. Depending on your operating system, this might differ.

The output is given below:

Output of print(sys.executable) in Python

By knowing this location, you can ensure that you are using the correct Python interpreter for your projects.

Troubleshooting Common Python Issues

In this section, we’ll talk about some common issues that you may face when working with Python paths.

Troubleshooting Common Python Issues

Let’s get into it!

1. Path-related Problems

For beginners, one common problem when using Python is related to file paths.

When Python is installed, its location may not be added automatically to the system environment variables PATH.

This could result in the “Python not found” error when trying to run Python scripts or access the Python shell.

To troubleshoot this issue, you can:

  1. Ensure Python is installed correctly by checking the installation folder, typically found in:
    • Windows: C:\Python{version}
    • macOS and Linux: /usr/local/bin/python{version}
  2. Add Python to the PATH variable to make it accessible system-wide:
    • Windows: Open the Control Panel, navigate to System and Security > System > Advanced system settings > System Environment Variables, and edit the PATH variable to include the Python installation folder.
    • macOS and Linux: Open the terminal and add the Python installation directory to the PATH variable using the export command, such as export PATH=/usr/local/bin/python{version}:$PATH.
  3. Save and restart the terminal or Command Prompt to apply the changes.

After following the steps above correctly, you’ll no longer run into any errors with running Python files.

2. Version Compatibility

Different Python versions might lead to version compatibility issues, especially when working with third-party modules and libraries.

To overcome this, you can:

  1. Check your Python version by running python –version in the terminal or Command Prompt.
  2. Verify the compatibility of a package by checking its documentation or the PyPI page. Packages usually list compatible Python versions.
  3. Use a virtual environment to manage and isolate dependencies for different projects.

By addressing path-related problems and ensuring version compatibility, you can resolve some of the most common Python issues.

To learn more about error resolution in Python, check the following video out:

Final Thoughts

Understanding where Python is installed on your system is a fundamental aspect of becoming an efficient programmer.

It allows you to manage your programming environment effectively and is key when dealing with using multiple versions of Python versions or when installing modules.

It also helps you in cases when you want to use specific versions for different projects, or when you need to install packages globally or just for one project.

Furthermore, knowing the path of your Python installation can also help you troubleshoot issues related to your environment setup or version conflicts and fine-tune your coding environment to your liking.

It’s an essential step in setting up an integrated development environment, and it makes using code editors or Python-related software smoother and more efficient!

Frequently Asked Questions

In this section, we’ve listed some frequently asked questions that most beginners have related to the Python installation directory.

Frequently Asked Questions

Where is Python install location on Windows?

Python is installed in the default location C:\PythonXY where XY represents the version number.

For example, C:\Python39 for Python 3.9. It might also get installed under C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.

How to find Python location in CMD?

To find the Python installation path in CMD, you can use the following command:

python -c 
import os, sys
print(os.path.dirname(sys.executable))

This command imports the os and sys modules and prints the directory of the Python executable.

Where is Python’s location in Windows 10?

On Windows 10, Python’s default location is C:\PythonXY or C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.

How to check if Python is installed?

To check if Python is installed, open a command prompt or terminal and type in:

python --version

If Python is installed, the command will display the version of Python.

If it’s not installed, you’ll get an error or the Microsoft Store may open for Python installations in certain cases on Windows.

How to find Python package’s installation location?

Python packages are generally installed in a subfolder of the Python installation. The specific location depends on whether you’re using a virtual environment or not.

To find the installation location of a package, open a terminal or command prompt and type:

pip show package-name

Replace “package-name” with the name of the package you want to find the location for. The output will show the package’s location along with other information.

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:

A screenshot of the Everything program searching for "python.exe"

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.

Steps to add Python to PATH

Below are the steps we must take to add python to our PATH variable.

  1. First, we must find the directory where we installed Python. A typical installation would have the following path, C:\Users\MyUserName\AppData\Local\Programs\Python\Python310

  2. Now, we will need to add this to the PATH variable, we right click on «This PC» and go to «Properties».

  3. Then, we click on the «Advanced system settings» in the menu on the left.going

  4. In the bottom right, we can see a button labeled «Environment Variables». We will click on it to open another window to edit these variables.

  5. Now, we select the «Path variable» in the «System variables» section and click «Edit». The next screen will show all the directories currently part of the PATH variable.

  6. Another window opens up where we can see all the paths for the currently configured system variables. To add a new path for our Python program, we will click on the «New» button on the right side and paste the path in Step 1

  7. We have successfully added the path for our Python program to our system’s environment variables. The best practice is to restart the system afterward for the change to occur.

  8. Now, we can verify if the PATH variable was configured correctly by opening up the terminal and entering the command python --version.

After all the following steps are completed, when we run the command on the command prompt, we should get a similar output to the one shown below

  • Директ икс скачать для windows 10 x64
  • Диск восстановления windows 10 на флешку скачать торрент
  • Директория 10 для windows 10 скачать
  • Диск восстановления windows 10 на dvd
  • Директ скачать бесплатно для windows 7 торрент