Ошибка python в командной строке

I have installed the latest Python for Win10 from Releases for Windows.
Just typing py in the Command Prompt Window starts Python.

Microsoft Windows [Version 10.0.15048]
(c) 2017 Microsoft Corporation. All rights reserved.

C:Userssg7>py
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>`enter code here`

Testing:

>>> print("hello!")
hello!
>>>

Please be aware that in my case Python was installed in C:Userssg7AppDataLocalProgramsPythonPython36> directory

C:Userssg7AppDataLocalProgramsPythonPython36>dir
 Volume in drive C is Windows7_OS
 Volume Serial Number is 1226-12D1

 Directory of C:Userssg7AppDataLocalProgramsPythonPython36

08/05/2018  07:38 AM    <DIR>          .
08/05/2018  07:38 AM    <DIR>          ..
12/18/2017  09:12 AM    <DIR>          DLLs
12/18/2017  09:12 AM    <DIR>          Doc
12/18/2017  09:12 AM    <DIR>          include
12/18/2017  09:12 AM    <DIR>          Lib
12/18/2017  09:12 AM    <DIR>          libs
10/03/2017  07:17 PM            30,334 LICENSE.txt
10/03/2017  07:17 PM           362,094 NEWS.txt
10/03/2017  07:15 PM           100,504 python.exe
10/03/2017  07:12 PM            58,520 python3.dll
10/03/2017  07:12 PM         3,610,776 python36.dll
10/03/2017  07:15 PM            98,968 pythonw.exe
08/05/2018  07:38 AM           196,096 Removescons.exe
08/05/2018  07:38 AM            26,563 scons-wininst.log
08/05/2018  07:38 AM    <DIR>          Scripts
12/18/2017  09:12 AM    <DIR>          tcl
12/18/2017  09:12 AM    <DIR>          Tools
06/09/2016  11:53 PM            87,888 vcruntime140.dll
               9 File(s)      4,571,743 bytes
              10 Dir(s)  20,228,898,816 bytes free

When I am at C:Userssg7> directory level python can be invoked by typing
AppDataLocalProgramsPythonPython36python

C:Userssamg>AppDataLocalProgramsPythonPython36python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Newer Python 3.7 will be installed at:
C:UsersYourUserNameHereAppDataLocalProgramsPythonPython37

If you wish you can add to your path environment variable:
%USERPROFILE%AppDataLocalProgramsPythonPython36

I’m trying to -learn to write and- run Python scripts on my Windows 7 64 bit machine. I installed Python in C:/Python34, and I added this to my Windows’ PATH variable :

C:Python34; C:Python34python.exe

(the second one is probably meaningless but I tried) and still I get this error in Windows command line :

C:Usersme>python test.py
'python' is not recognized as an internal or external command,
operable program or batch file.

So how do I truly install Python on my Windows x64 machine ?

asked Jun 12, 2014 at 14:22

jeff's user avatar

3

This might be trivial, but have you tried closing your command line window and opening a new one? This is supposed to reload all the environment variables.
Try typing

echo %PATH%

into the command prompt and see if you can find your Python directory there.

Also, the second part of your addition to the PATH environment variable is indeed unnecessary.

answered Jun 12, 2014 at 14:28

yossim's user avatar

yossimyossim

3062 silver badges5 bronze badges

7

I had the same problem: python not being recognized, with python in the path which was was not truncated.

Following the comment of eryksun in yossim’s answer:

Also, if you installed for all users you should have %SystemRoot%py.exe, which >is typically C:Windowspy.exe. So without setting Python’s directory in PATH >you can simply run py to start Python; if 2.x is installed use py -3 since >Python 2 is the default. – eryksun

I tried to use py instead of python and it worked.
Meaning:
python setup.py build -> does NOT work.
py setup.py build -> does work.
Hope it helps

Josef Ginerman's user avatar

answered Sep 21, 2017 at 14:17

senis000's user avatar

senis000senis000

2412 silver badges6 bronze badges

1

I did everything:

  • Added Python to PATH
  • Uninstall all the Pythons — Both from downloaded python.org and Microsoft Store and reinstall from python.org
  • Change the order of PATH
  • Deleted %USERPROFILE%AppDataLocalMicrosoftWindowsApps from PATH

But nothing worked. What worked for me was:
Settings > Application > App execution aliases. Then disable all the Pyhtons from here and it worked!
App execution aliases

answered Dec 2, 2022 at 14:05

tatoline's user avatar

tatolinetatoline

3415 silver badges11 bronze badges

5

I was also having the same problem.

Turns out the path I added included ‘..python.exe’ at the end, which as turns out was not required. I only needed to add the directory in which ‘python.exe’ is in (which in my case is the Anaconda’s distribution directory in Users folder), similar to what we do when installing JDK in our system’s PATH variable.

Hope it helps!

answered Jul 29, 2018 at 4:54

Arnab Roy's user avatar

Arnab RoyArnab Roy

3073 silver badges8 bronze badges

It wasn’t working for me even after adding the path. What finally did the trick, was changing the order of listed paths in the PATH variable. I moved %USERPROFILE%AppDataLocalMicrosoftWindowsApps down vs. having it the first path listed there.

vvvvv's user avatar

vvvvv

24.2k19 gold badges48 silver badges76 bronze badges

answered Apr 3, 2022 at 6:50

uditgt's user avatar

uditgtuditgt

1291 silver badge1 bronze badge

3

Environment PATH Length Limitation is 1024 characters

If restarting your cmd window does not work you might have reached the character limit for PATH, which is a surprisingly short 1024 characters.

Note that the user interface will happily allows you to define a PATH that is way longer than 1024, and will just truncate anything longer than this. Use

echo %PATH%

in your cmd window to see if the PATH being truncated.

Solution

Unfortunately, there is no good way to fix this besides removing something else from your PATH.


NOTE: Your PATH = SYSTEM_PATH + USER_PATH, so you need to make sure the combined is < 1024.

Community's user avatar

answered Jun 12, 2014 at 15:00

bcorso's user avatar

bcorsobcorso

45.3k10 gold badges63 silver badges75 bronze badges

1

Also, make sure to leave no spaces after the semi-colon.

For example, this didn’t work for me:
C:Windowssystem32; C:Python27; C:Python27Scripts;

But, this did:
C:Windowssystem32;C:Python27;C:Python27Scripts;

answered Mar 29, 2018 at 17:21

nihal111's user avatar

nihal111nihal111

3683 silver badges9 bronze badges

2

I’m late to the game here, but I’d like to share my solution for future users. The previous answers were on the right track, but if you do not open the CMD as an administrator, then you will be thrown that same error. I know this seems trivial and obvious, but after spending the past 8 hours programming before attempting to install Django for the first time, you might be surprised at the stupid mistakes you might make.

answered Jan 30, 2015 at 17:40

David Schilpp's user avatar

1

I had the same issue with Python 2.7 on Windows 10 until I changed the file path in Enviroment Variables to the folder path, ie C:Python27python.exe didn’t work but C:Python27 did work.

answered Oct 31, 2018 at 12:33

Nick W's user avatar

Nick WNick W

8772 gold badges15 silver badges28 bronze badges

1

I have faced same problem even though my path contains 400 characters.
Try to update the path from the command line(Run as administrator)

Command to update path: setx path «%path%;c:examplePath»

After this command I could see that paths that I configured earlier in environment variables got updated and working.

To check the configured paths: echo %PATH%

answered Jul 4, 2019 at 6:23

Manikanta Vasupalli's user avatar

1

I was facing similar porblem. What helped me is where command.

C:WINDOWSsystem32>where python
C:UsersxxxxxxxAppDataLocalMicrosoftWindowsAppspython.exe
C:Program Files (x86)Microsoft Visual
StudioSharedPython39_86python.exe

On updating PATH variable to point to only one desired directory (basically I removed %USERPROFILE%AppDataLocalMicrosoftWindowsApps from PATH) fixed my problem.

answered Mar 31, 2022 at 8:00

Manojkumar Khotele's user avatar

If you run into this issue like I just did, save yourself some time and reboot your entire computer, not just your terminal. This fixed it instantly for me.

answered Feb 28 at 2:50

KCP's user avatar

1

For me, installing the ‘Windows x86-64 executable installer’ from the official python portal did the trick.

Python interpreter was not initially recognized, while i had installed 32 bit python.
Uninstalled python 32 bit and installed 64 bit.

So, if you are on a x-64 processor, install 64bit python.

answered Mar 11, 2019 at 15:42

dev ip's user avatar

I tried it multiple times with the default installer option, the first one, (Python 3.7.3) with both ‘add to environment variable’ and ‘all users’ checked, though the latter was greyed out and couldn’t be unchecked.

It failed to work for other users except for the user I installed it under until I uninstalled it and chose «Custom Install». It then clearly showed the install path being in the C:Program FilesPython37 directory when it was failing to install it there the other way even though the ‘All Users’ option was checked.

answered May 16, 2019 at 1:08

mindmischief's user avatar

Same thing was happening with me when i was trying to open the python immediately with CMD.

Then I kept my in sleep mode and started CMD using these Key Windows_key+R, typed cmd and OK. Then the package of python worked perfectly.

Matthew's user avatar

Matthew

1,9053 gold badges19 silver badges26 bronze badges

answered Jun 20, 2019 at 9:15

Creepy Creature's user avatar

  1. Uninstall python and pyqt
  2. Then go to pyqt setup and open installation but don’t install. You will see a message box saying something like pyqt version built with python version 32bit/64bit.
  3. Then see python version bit and download that version from python.org from all release menu.
  4. Then first install python and then install pyqt. It will work like butter.

Mohannad A. Hassan's user avatar

answered Nov 30, 2019 at 23:41

Mark S. Khalil's user avatar

1

I spent sometime checking and rechecking the path and restarting to no avail.

The only thing that worked for me was to rename the executable C:Python34python.exe to C:Python34python34.exe. This way, calling typing python34 at the command line now works.

On windows it seems that when calling ‘python’, the system finds C:Python27 in the path before it finds C:Python34

I’m not sure if this is the right way to do this, seems like a hack, but it seems to work OK.

answered Jan 8, 2015 at 18:41

maulynvia's user avatar

1

Сегодня поговорим об установке Python и о первых проблемах с которыми могут столкнуться начинающие программисты. После установки Python все советую проверит правильность его установки введя в командной строке Python, после этого вы должны увидеть установленную версию питона. Так же вы сможете вводим простенькие команды и выполнять их через командную строку например, введя print(«привет»), код должен выполниться и отобразить просто «Привет».

Для установки различных модулей используется PIP, например, для установки requests в командной строке нужно ввести pip install requests. Вообще большинство пользователей после установки питона и введя в командной строке «PIP» или «Python» получает сообщение об ошибке «не является внутренней или внешней командой, исполняемой программой или пакетным файлом».

Решение данный проблемы очень простое, в интернете очень много ответов, но все они очень краткие, сжатые, без скриншотов. Разобраться новичку будет достаточно сложно. Большинство ответов имеют вот такой вид

«Вам нужно установить путь к pip в переменные окружения»

Думаю новичку это абсолютно ни о чем не говорит, он еще больше запутается. Поэтому я решил подробно описать решение данной проблемы.

Простое решение проблемы в Windows 10

И так при вводе в командной строке PIP вы видите сообщение.

«PIP» не является внутренней или внешней командой, исполняемой программой или пакетным файлом

PIP не является внутренней или внешней командой

Тоже самое и с Python

«Python» не является внутренней или внешней командой, исполняемой программой или пакетным файлом

Python не является внутренней или внешней командой,

Вам нужно добавить значения в переменную Path, рассказывать что это не буду, просто открываем свойства компьютера и выбираем «Дополнительные параметры системы».

Ошибка pip не является внутренней или внешней командой,

Далее в свойствах системы переходим во вкладку «Дополнительно» и снижу нажимаем «Переменные среды».

что делать python не является внутренней или внешней командой,

В открывшемся окне в верхней части отмечаем переменную «Path» и нажимаем изменить.

Переменные среды пользователя

В поле «Значение переменной» дописываем путь до папки в которой у вас установлен Питон, в моем случае это С:Python, так же нужно указать путь до папки где лежит файл pip.exe у меня это С:PythonScripts. Дописываем через ; вот так.

С:PythonScripts;С:Python;

Сохраняем.

Рекомендую изменять стандартный путь установки Питона на С:Python.

Как дописать значение в переменную path

Теперь проверяем результат запускаем командную строку и пишем сначала «PIP».

PIP как проверить команду

Потом пробуем написать «Python», после шеврона (>>>) можно уже написать какой нибудь код например, print(«Привет!»).

Питон выполнение кода в командной строке

Если выше описанное для вас сложно, то можно переустановить сам Питон, отметив в главном окне пункт «Add Python 3.9 to PATH».

add python to path

В процессе установки все пути будут прописаны автоматически. Вот так можно избавиться от ошибки «не является внутренней или внешней командой, исполняемой программой или пакетным файлом», которая появляется в командной строке при вводе «PIP» или «Python».

Что означает ошибка ModuleNotFoundError: No module named

Что означает ошибка ModuleNotFoundError: No module named

Python ругается, что не может найти нужный модуль

Python ругается, что не может найти нужный модуль

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

import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)
zeros = np.zeros((5, 4))
lin = np.linspace(1, 10, 20)

Копируем, вставляем в редактор кода и запускаем, чтобы разобраться, как что работает. Но вместо обработки данных Python выдаёт ошибку:

❌ModuleNotFoundError: No module named numpy

Странно, но этот код точно правильный: мы его взяли из блога разработчика и, по комментариям, у всех всё работает. Откуда тогда ошибка?

Что это значит: Python пытается подключить библиотеку, которую мы указали, но не может её найти у себя.

Когда встречается: когда библиотеки нет или мы неправильно написали её название.

Что делать с ошибкой ModuleNotFoundError: No module named

Самый простой способ исправить эту ошибку — установить библиотеку, которую мы хотим подключить в проект. Для установки Python-библиотек используют штатную команду pip или pip3, которая работает так: pip install <имя_библиотеки>. В нашем случае Python говорит, что он не может подключить библиотеку Numpy, поэтому пишем в командной строке такое:

pip install numpy

Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.

Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:

Что означает ошибка ModuleNotFoundError: No module named

А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.

Вёрстка:

Кирилл Климентьев

prim0

a53e06407f7f46df82d99b9f6184b52a.PNG3513624638ff4f809b8aa04a94af49a3.PNG


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

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

  • 18251 просмотр


Комментировать


Решения вопроса 2

saboteur_kiev

Saboteur

@saboteur_kiev Куратор тега Python

software engineer

А собственно сам питон вы на комп устанавливали?
Где находится python.exe можете показать?

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


Ответы на вопрос 3

RusTech

pyton как и piton не запустятся с командной строки

КАКОЙ PYTON?????? PYTHON!!!!!!!!!!!!!!!!!!!!]


Комментировать


Похожие вопросы


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

13 июн. 2023, в 17:21

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

13 июн. 2023, в 17:10

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

13 июн. 2023, в 17:07

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

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

Понравилась статья? Поделить с друзьями:
  • Ошибка prototype 2 не поддерживается этот формат экрана
  • Ошибка python m pip install upgrade pip
  • Ошибка protocol error русификатор my summer car
  • Ошибка python invalid continuation byte
  • Ошибка protect на музыкальном центре sony