Как найти python interpreter

Добрый день, есть Linux Mint, поставил PyCharm, написал программу. Запускаю из PyCharm — работает.

Запускаю через командную строку python3 test.py — выдает ошибку, не может найти библиотеки.
Как я понимаю есть несколько интерпретаторовокружений.

Как бы мне выяснить с какими параметрами я запускаю в PyCharm и также запустить в командной строке?


  • Вопрос задан

    более трёх лет назад

  • 54394 просмотра

Пригласить эксперта

попробуйте команду which он укажет где находится исполняемый файл.
Пример:
which python3
Ответ: будет примерно
/usr/bin/python3

в Window 10 путь к интерпретатору python по-умолчанию можно узнать через команду where python

#держувкурсе

Если создавали проект через PyCharm — то по умолчанию используется venv в папке с проектом.
Чтобы активировать venv из терминала — выполните команду source venv/bin/activate, находясь при этом в папке с проектом

В PyCharm есть встроенный терминал, вызывается по сочетанию клавиш Alt + F12. В нем venv уже активирован.

В каталоге доустановить библиотеки «в ручную», набрав в консоли: pip install название_библиотеки


  • Показать ещё
    Загружается…

29 мая 2023, в 08:59

500 руб./за проект

29 мая 2023, в 08:57

20000 руб./за проект

29 мая 2023, в 08:57

140000 руб./за проект

Минуточку внимания

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

23.1k27 gold badges120 silver badges222 bronze badges

asked Mar 15, 2009 at 9:09

Fang-Pen Lin's user avatar

Fang-Pen LinFang-Pen Lin

13.2k15 gold badges66 silver badges95 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,6991 gold badge14 silver badges17 bronze badges

3

It would be either of

  • C:Python36
  • C:Users(Your logged in User)AppDataLocalProgramsPythonPython36

answered Aug 18, 2017 at 9:52

Amol Manthalkar's user avatar

Amol ManthalkarAmol Manthalkar

1,8602 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:

  • HKLMSOFTWAREPythonPythonCoreversionnumberInstallPath
  • HKCUSOFTWAREPythonPythonCoreversionnumberInstallPath

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

  • HKLMSOFTWAREWow6432NodePythonPythonCoreversionnumberInstallPath

yincrash's user avatar

yincrash

6,3341 gold badge39 silver badges41 bronze badges

answered Mar 15, 2009 at 21:08

codeape's user avatar

codeapecodeape

97.2k24 gold badges156 silver badges186 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,1311 gold badge14 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:UserscscottAppDataLocalProgramsPythonPython38-32python.exe *
-2.7-64 C:Python27python.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

5,9743 gold badges29 silver badges34 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

82.8k10 gold badges76 silver badges104 bronze badges

2

Its generally

‘C:Usersuser-nameAppDataLocalProgramsPythonPython-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.3k3 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

4,99912 gold badges43 silver badges60 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%AppDataLocalProgramsPythonPython_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,6584 gold badges23 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:Windowspy.exe if installed for all users, otherwise can be found at C:UsersusernameAppDataLocalProgramsPythonLauncher.
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

3493 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:UsersusernameAppDataLocalProgramsPythonPython310

Very handy if you use python pip to install packages.

Suraj Rao's user avatar

Suraj Rao

29.3k11 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(@"PythonPythonCore");
    if (pythonCoreKey == null)
        pythonCoreKey = key.OpenSubKey(@"Wow6432NodePythonPythonCore");
    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

36.7k38 gold badges141 silver badges197 bronze badges

2

This worked for me: C:UsersYour_user_nameAppDataLocalProgramsPython

My currently installed python version is 3.7.0

Hope this helps!

David's user avatar

David

1,1825 gold badges13 silver badges30 bronze badges

answered Jul 16, 2018 at 6:55

Prashant Gonga's user avatar

Go to C:UsersUSERAppDataLocalProgramsPythonPython36
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…

venvscriptsactivate.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:UsersakshayAppDataLocalProgramsPythonPython36

Kos's user avatar

Kos

4,8709 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 FilesPython37python.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,5366 gold badges41 silver badges79 bronze badges

Option 1 : Check System Environment Variables > Path

Option 2 : C:UsersAsusAppDataLocalProgramsPython (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}SoftwarePythonPythonCore*InstallPath"

answered Mar 27 at 23:26

Harry Zhang's user avatar

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these.
Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
'/usr/bin/pythonn'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/pythonn'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/pythonn'
>>>
>>>

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $ 

Иногда нам нужно проверить пакеты или модули по пути, где установлен 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».

[toc]

Introduction

Problem Statement: How to find the full path of the currently running Python interpreter?

There are different ways to find the full path of Python interpreters. But first, let’s get the basics out of our way before we unearth the solution to our problem statement.

So, what’s a Python Interpreter? This might be a bit silly to discuss for intermediate coders, however keeping in mind the wide range of audience we have, it is absolutely necessary to understand the basics before we dissect the given question. Please feel free to jump into the solutions right away if you already know what are interpreters.

The Python Interpreter

In simple terms, interpreter is the layer that operates between your program and your computer hardware to get your code running. The Python interpreter is a byte-code interpreter. We will learn about bytecodes in some other discussion but for now you can think of bytecode as a series of instructions or a certain low level program for the Python Interpreter. Each code object contains a bunch of instructions to be executed that is the bytecode in addition to the other data that the interpreter will require.

The interpreter runs the Python code in two different ways:

  • Script or Module
  • A piece of code in an interactive session

Finding Python Path

When you get introduced to Python, you first install it on your device. If you are on a Windows machine, it is most likely the situation that there is a file named C:Python, and inside that file, there is a program named python.exe. Hence, the path to Python is C:Python. It can also be installed at the following path: C:Program FilesPython.  On the off chance that you have no clue about where Python got installed on your device, you should look for it in the following way: 

  1. First, press Start in the lower-left corner then press Search followed by all files and folders. 
  2. Type python.exe in the top text line that shows up and then press the search. 
  3. A folder name will be listed where Python got installed. Hence the folder name becomes the path of Python.
  4. Now, go to the particular folder path and ensure that python.exe belongs inside the folder.

Now let’s dive into the various methods to find the full path of a Python interpreter.

Method 1: Using sys.executable

At a point when the Python script runs, the sys.executable gives the path to the program that was executed, to be specific, the Python interpreter. In case if Python is not able to recover the genuine path to its executable, the sys.executable method will be an empty string or None.

According to the official documentation, sys.executable gives a string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

Note: You have to import the sys module to utilize it.

Example:

While using it in your script, you can do it this way:

import sys
path = sys.executable
print(path)

Method 2: Using sys.path

Most often beginners intend to install the wrong interpreter module or package in Python. The system then does not allow to import the desired packages. Hence, it becomes necessary to find the right path for the interpreter. You can use the sys.path variable for this purpose.

The sys.path variable is a list of strings that determines the path for the modules, and it also tells where the packages (commonly with pip) have been installed.

Example:

While using it in your script, you can do it this way:

# Importing sys module
import sys
path = sys.path
# Getting the path of the Python interpreter
print(path)

Conclusion

I hope this has been informative. Please stay tuned and subscribe for more tutorials in the future.

Recommended Tutorial: How Do I Copy a File in Python?


Finxter Computer Science Academy

  • One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • So, do you want to master the art of web scraping using Python’s BeautifulSoup?
  • If the answer is yes – this course will take you from beginner to expert in Web Scraping.

shubham finxter profile image

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

Понравилась статья? Поделить с друзьями:
  • Как исправить кабель теплого пола
  • Как найти киприана буркова
  • Как найти объем призмы по векторам
  • Как найти слова категории состояния в тексте
  • Как найти косинус если известны три стороны