Лайфхаки

Маленькие, полезные хитрости

Как изменить PYTHONPATH на Windows. Using PYTHONPATH ¶

29.05.2023 в 19:37

Как изменить PYTHONPATH на Windows. Using PYTHONPATH ¶

PYTHONPATH is an.

The PYTHONPATH variable has a value that is a string with a list of directories that Python should add to thedirectory list.

The main use of PYTHONPATH is when we are developing some code that we want to be able to import from Python, but that we have not yet made into an installable Python package (see:making a Python package).

Returning to the example module and script in:

Before we set PYTHONPATH correctly, a_script.py will fail with:

Now I set the PYTHONPATH environment variable value to be the path to the code directory:

$ # Set PYTHONPATH to path to the working directory + /code $ # This is for the "bash" shell on Unix / git bash on Windows $ export PYTHONPATH = " $PWD /code" $ # Now the script can find "a_module" $ python3 scripts/a_script.py Running useful function

Setting PYTHONPATH more permanently

You probably don’t want to have to set PYTHONPATH every time you start up a terminal and run a Python script.

Luckily, we can make the PYTHONPATH value be set for any terminal session, by setting the environment variable default.

For example, let’s say I wanted add the directory /Users/my_user/code to the PYTHONPATH:

If you are on a Mac

    Open Terminal.app ;

    Save the file.

    Close Terminal.app ;

If you are on Linux

    Open your favorite terminal program;

    Close your terminal application;

If you are on Windows

Got to the Windows menu, right-click on “Computer” and select “Properties”:

From the computer properties dialog, select “Advanced system settings” on the left:

From the advanced system settings dialog, choose the “Environment variables” button:

In the Environment variables dialog, click the “New” button in the top half of the dialog, to make a new user variable:

Give the variable name as PYTHONPATH and the value is the path to the code directory. Choose OK and OK again to save this variable.

Now open a cmd Window (Windows key, then type cmd

to confirm the environment variable is correctly set.

If you want your IPython sessions to see this new PYTHONPATH variable, you’ll have to restart your terminal and restart IPython so that it picks up PYTHONPATH from the environment settings.

Как добавить Python в PATH mac. How to Add Python to PATH

You may need to add Python toPATHif you’ve installed Python, but typingpythonon the command line doesn’t seem to work. You may be getting a message saying that the termpythonisn’t recognized, or you may end up with the wrong version of Python running.

A common fix for these problems is adding Python to thePATH. In this tutorial, you’ll learn how to add Python toPATH. You’ll also learn about whatPATHis and whyPATHis vital for programs like the command line to be able to find your Python installation.

Note: A path is the address of a file or folder on your hard drive. ThePATHenvironment variable, also referred to as justPATHor Path , is a list of paths to directories that your operating system keeps and uses to find executable scripts and programs.

The steps that you’ll need to take to add something toPATHwill 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 toPATH, not just Python.

Supplemental Code: Click here to download free supplemental code that’ll walk you through changing PATH across operating systems.

How to Add Python toPATHon 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 thePATHenvironment variable.

To find the Python executable, you’ll need to look for a file calledpython.exe. The Python executable could be in a directory inC:\Python\or in yourAppData\folder, for instance. If the executable were inAppData\, then the path would typically look something like this:

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

In your case, the

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\WindowsAppsand\Python310, would be ideal candidates to add toPATHbecause 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 seevenvin 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.

Как добавить pycharm в PATH. Installing PyCharm:

Step 1: Visit the following link to download PyCharm. Click the download button under the community part.

Step 2: After downloading, run the .exe file for installation. Click next once the installation screen appears.

Step 3: On the next screen click next. If you want, you can change the installation path of the PyCharm.

Step 4: Select all the checkboxes from the next screen and click next.

  • Create Desktop Shortcut option creates a shortcut of PyCharm IDE on the desktop for 64 bit operating systems.
  • Update Path Variable options help you to approach PyCharm from the Command Prompt directly.
  • Update Context Menu helps you to be able to right-click on any folder in your computer and to have the option to open this folder as a project in PyCharm.
  • Create Associations option helps to open your .py extension files in PyCharm IDE

Step 5: Next screen is “Choose menu folder”. Click Jetbrains as is and click install.

Step 6: Installation of PyCharm will take some time. Wait till it completes.

Step 7: On the next screen, click the “Reboot now” option to complete the PyCharm setup. Click finish and then your computer will be restart.

Step 8: Once your pc restarts, open the PyCharm application. If the following screen appears, then select “Do not import settings” and click the OK button.

Step 8: On the next “Customize PyCharm” screen, select the theme you like and click the “Next: featured plugins” button.

Step 9: After that Download any plugins if you want, otherwise click the “Start using PyCharm” button.

Step 10: After that “Welcome to PyCharm” screen will appear. Now PyCharm installation is successfully completed. Click the “Create New Project” button and start creating awesome python projects.

PATH Python Windows. Автоматически добавлять Python в Windows PATH

Вы также можете автоматически добавить Python в PATH Windows во время установки. Хотя этот метод работает не во всех случаях, вы все равно можете попробовать.

Для этого щелкните свой установочный файл и установите флажок « Добавить Python 3.7 в PATH» . Номер версии будет меняться при установке разных версий Python.

Установка этого флажка автоматически добавляет Python в ваш путь к Windows. Это означает, что вы можете запускать команды Python через командную строку сразу после установки.

Подтвердите, что Python добавлен в Windows PATH

Чтобы узнать, добавлен ли Python в PATH Windows, откройте терминал и введите  python —version , затем нажмите  клавишу Enter . Если команда возвращает текущую установленную версию Python, это означает, что вы успешно добавили ее в Windows PATH.

Однако, чтобы проверить, добавили ли вы каталог  Scripts  в Windows PATH, попробуйте запустить  пакет установки pip  на терминале, заменив «package» на предпочитаемую вами библиотеку. Если вы установили  Python 2.7.9  и выше, команда устанавливает названный пакет, указывая, что вы также успешно добавили скрипты Python в путь.

Помимо добавления Python в PATH Windows, вы можете добавить текстовые редакторы, интегрированные среды разработки (IDE), Git, Node, Anaconda и многие другие программы.

Например, управлять проектом с помощью Sublime Text легко, когда вы открываете терминал в каталоге папки вашего проекта и запускаете  subl.  команда. Это откроет редактор в вашей текущей папке и отобразит его на боковой панели, еще один экономящий время ярлык для продуктивной работы с Sublime Text.

Как добавить Python в PATH Window. Add Python to the Windows Path

If you’ve installed Python in Windows using the default installation options, the path to the Python executable wasn’t added to the Windows Path   variable . The Path variable lists the directories that will be searched for executables 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 by typing the python keyword (you won’t need to specify the full path to the program).

Consider 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 output above, the command was not found. To run python.exe , you need to specify the full path to the executable:

C:\>C:\Python34\python --version Python 3.4.3

Как добавить Python в PATH Window.  Add Python to the Windows Path

This should open up the System Properties window. Go to the Advanced tab and click the Environment Variables button:

Как добавить Python в PATH Window.  Add Python to the Windows Path

Как добавить Python в PATH Window.  Add Python to the Windows Path

Position your cursor at the end of the Variable value line and add the path to the python.exe file, preceeded with the semicolon character ( ; ). In our example, we have added the following value:  ;C:\Python34

Как добавить Python в PATH Window.  Add Python to the Windows Path

Close all windows. Now you can run python.exe without specifying the full path to the file:

C:>python --version Python 3.4.3

If you get the ‘python’ is not recognized as an internal or external command, operable program or batch file.  error, there is something wrong with your Path variable. Note also that you will have to reopen all command prompt windows in order for changes to the Path variable take effect.

Geek University recommends the following video course to get you started in Python.

Как добавить в PATH Window. Что такое переменная Path и зачем она нужна в Windows. Зачем нужно добавлять путь?

PATH – это системная переменная окружения Unix-подобных (например, Linux Mint ) операционных систем, а также операционных систем семейства Windows. В переменной PATH нет ничего сложно и хитрого, это обыкновенный список папок и каталогов, в которых лежат исполняемые файлы (программы). Программы, путь к исполняемым файлом которых задан в системной переменной PATH, могут быть исполнены (запущены) непосредственно из командной строки Windows и из любого места вашей файловой системы (в Linux тоже есть командная строка, но ее лучше называть эмулятор терминала ).

Давайте лучше посмотрим на примере зачем нужна переменная PATH в операционных системах семейства Windows (как, впрочем, и в других семействах). Смотреть будем на примере сторонней утилиты командной строки Windows tracetcp.exe. Она у меня установлена по следующему пути: c:\Program Files\tracetcp\. Запустим командую строку Windows и попробуем выполнить команду tracetcp.

Пробуем запустить стороннюю утилиту командной строки Windows

Обратите внимание на то, что командная строка не смогла выполнить команду tracetcp, хотя приложение и установлено на мой компьютер, проблема заключается в том, что командная строка не смогла найти исполняемый файл tracetcp.exe . Но где командная строка его искала? Она искала этот файл в текущем каталоге, то есть в данном случае в каталоге: c:\Users\Dell, там этого файла не оказалось, затем командная строка обратилась к переменной PATH, там она не обнаружила пути к исполняемому файлу tracetcp.exe, но обнаружила путь к папке System32, проверила, что в этой папке также нет файла tracetcp.exe и выдала нам предупреждение: «"tracetcp" не является внутренней или внешней командой, исполняемой программой или пакетным файлом.».

Поскольку мы находились в папке, отличной от той, где находится файл tracetcp.exe, а пути в переменной PATH к этому файлу не оказалось, командная строка просто не смогла его найти , чтобы исполнить, давайте всё-таки его запустим, для этого нужно будет перейти в папку c:\Program Files\tracetcp при помощи команды cd (в операционных системах Linux тоже есть команда cd и работает она аналогично), а затем запустить утилиту.

Запуск исполняемого файла в командной строке Windows

Теперь командная строка Windows смогла запустить нашу утилиту, поскольку смогла найти исполняемый файл tracetcp.exe, но каждый раз переходить в папку, где лежит исполняемый файл или каждый раз указывать абсолютный путь к исполняемому файлу — это очень неудобно, будет гораздо лучше, если мы укажем путь к исполняемому файлу в переменной PATH , тогда командная строка будет самостоятельно его находить в любое время и в любом месте.

Исполняемый файл был запущен, поскольку путь до него был добавлен в системную переменную Path

На рисунке выше показано, что командная строка смогла запустить приложение из домашней папки пользователя, но это лишь благодаря тому, что я добавил путь исполняемому файлу в переменную PATH , теперь команда tracetcp будет работать из любой другой папки. Утилита tracetcp довольно простое приложение, представляющее собой один исполняемый файл — tracetcp.exe, можно было бы не прописывать путь в переменную PATH, а просто скопировать этот файл в папку System32, но устанавливать сторонние и непроверенные приложения, не требующие наличия файлов в System32, не самая хорошая и безопасная затея. В Windows лучше потратить немного времени на то, чтобы добавить путь к файлу в переменную PATH , о том как это сделать мы и поговорим ниже, рассмотрев этот процесс для операционных систем Windows 10, Windows 8 и Windows 7 .

Как настроить PYTHONPATH. How to set Python environment variable PYTHONPATH on Windows?

On Windows, you can set the PYTHONPATH environment variable to specify the directories that Python should search for modules when importing them. Here are several ways to set the PYTHONPATH environment variable on Windows:

1. Set PYTHONPATH using Command Prompt

$set PYTHONPATH=c:\path\to\my\modules

This sets the PYTHONPATH environment variable to c:\path\to\my\modules. To make this change permanent, you need to add it to the system environment variables:

Open the Start menu and search for "Environment Variables".

Click on "Edit the system environment variables".

Click on the "Environment Variables" button.

Under "System Variables", click on "New" to add a new environment variable.

Enter PYTHONPATH for the variable name and c:\path\to\my\modules for the variable value.

Click "OK" to save the environment variable.

2. Set PYTHONPATH using PowerShell

$env:PYTHONPATH = "c:\path\to\my\modules"

This sets the PYTHONPATH environment variable to c:\path\to\my\modules. To make this change permanent, you can add it to your PowerShell profile:

Open PowerShell and enter the following command to open your PowerShell profile:

$notepad $PROFILE

Add the following line to the end of the file:

$env:PYTHONPATH = "c:\path\to\my\modules"

Save the file and close Notepad.

3. Set PYTHONPATH using the Windows Environment Variables dialog

You can also set the PYTHONPATH environment variable using the Windows Environment Variables dialog. Here's how:

Open the Start menu and search for "Environment Variables".

Click on "Edit the system environment variables".

Click on the "Environment Variables" button.

Under "User Variables" or "System Variables", click on "New" to add a new environment variable.

Enter PYTHONPATH for the variable name and c:\path\to\my\modules for the variable value.

Click "OK" to save the environment variable.

4. Set PYTHONPATH using an IDE or editor

Many Python IDEs and text editors allow you to set environment variables directly from within the application. For example, in PyCharm, you can set the PYTHONPATH environment variable by going to Run > Edit Configurations and adding it to the environment variables section.

5. Set PYTHONPATH using a batch file

You can also create a batch file to set the PYTHONPATH environment variable. Here's an example:

$@echo off $set PYTHONPATH=c:\path\to\my\modules $python my_script.py

This sets the PYTHONPATH environment variable to python modules

To set the PYTHONPATH environment variable using a batch file on Windows, follow these steps:

Open a text editor such as Notepad and create a new file.

Add the following line to the file:

$set PYTHONPATH=path\to\your\python\module.

Replace path\to\your\python\module with the actual path to the folder containing your Python module or package.

Save the file with a .bat extension, for example setpythonpath.bat.

You can now run this batch file to set the PYTHONPATH environment variable. To do so, open a Command Prompt window and navigate to the directory where the batch file is located. Then, type the name of the batch file and press Enter. The PYTHONPATH environment variable will be set for the current Command Prompt session.

If you want to set the PYTHONPATH environment variable permanently, you can add the batch file to your system's startup folder. To do so, follow these steps:

Press the Windows key + R to open the Run dialog box.

Как удалить старую версию Python Window. Полностью удалите Python из Windows

В программном обеспечении Python есть много ошибок, которые время от времени необходимо исправлять. В Python также есть много устаревших типов пакетов и библиотек. По этим причинам всегда необходимо удалить старую версию программного обеспечения Python и загрузить обновленную, чтобы максимально использовать ее при написании любой программы. Следовательно, есть разные способы удалить старую версию программного обеспечения Python в разных операционных системах, таких как Mac, Windows и Linux.

В этом руководстве основное внимание уделяется демонстрации того, как окончательно удалить программное обеспечение Python с устройства Windows.

Окончательно удалить Python с помощью панели управления

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

Python - V

После нажатия Enter будет возвращена текущая версия программного обеспечения Python. Ниже представлен результат.

Python 2.7.0

Используйте панель управления для удаления Python.

Перейдите в панель управления из панели задач окна. После открытия панели управления выберите опциюУдалить программу. Появится список всех программ, которые в настоящее время установлены на компьютере. После этого введите в поисковой строкеPython. После поиска будет отображено программное обеспечение Python с его текущей версией. Наконец, выберите опциюудалить, чтобы удалить программное обеспечение.

Повторно проверьте наличие установленных версий Python.

Снова введите команду, указанную в ШАГЕ 1, в командной строке, чтобы проверить, установлено ли программное обеспечение Python. После нажатия Enter в командной строке должен отобразиться следующий оператор.