Adding Python to Path on Windows

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

You know what has worked for me really well on windows.

My Computer > Properties > Advanced System Settings > Environment Variables >

Just add the path as C:\Python27 (or wherever you installed python)

OR

Then under system variables I create a new Variable called PythonPath. In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path

Sample Image

This is the best way that has worked for me which I hadn't found in any of the docs offered.

EDIT: For those who are not able to get it,
Please add

C:\Python27;

along with it. Else it will never work.

How can I find where Python is installed on Windows?

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))"

Python - Faster way to set python path on windows?

According to this post all you have to do is type this in Command Prompt:

setx path "%path%;C:\Python27;"

Why would I add python to PATH

PATH is an environment variable in Windows. It basically tells the commandline what folders to look in when attempting to find a file. If you didn't add Python to PATH then you would call it from the commandline like this:

C:/Python27/Python some_python_script.py

Whereas if you add it to PATH, you can do this:

python some_python_script.py

Which is shorter and neater. It works because the command line will look through all the PATH folders for python and find it in the folder that the Python installer has added there.

The reason it's unticked by default is partly because if you're installing multiple versions of Python, you probably want to be able to control which one your commandline will open by default, which is harder to do if both versions are being added to your PATH.

Windows path in Python

you can use always:

'C:/mydir'

this works both in linux and windows.
Other posibility is

'C:\\mydir'

if you have problems with some names you can also try raw string literals:

r'C:\mydir'

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)

or

pathlib.Path(mydir) / myfile


Related Topics



Leave a reply



Submit