Path information sources
-
Environment variables: Python environment variables, such as PYTHONPATH, tell Python where to find modules on disk.
-
Current directory: You can change the current Python directory so that it can locate any modules used by your application.
-
Default directories: Even when you don’t define any environment variables and the current directory doesn’t yield any usable modules, Python can still find its own libraries in the set of default directories that are included as part of its own path information.
How to find path information
It’s helpful to know the current path information because the lack of a path can cause your application to fail. The following steps demonstrate how you can obtain path information:-
Open the Python Shell.
You see the Python Shell window appear.
-
Type import sys and press Enter.
-
Type for p in sys.path: print(p) in a new cell and click Run Cell
You see a listing of the path information, as shown in the figure below. Your listing may be different from the one shown in the figure, depending on your platform, the version of Python you have installed, and the Python features you have installed.
Another way to find paths
The sys.path attribute is reliable but may not always contain every path that Python can see. If you don’t see a needed path, you can always check in another place that Python looks for information. The following steps show how to perform this task:-
In a new cell, type import os and press Enter.
-
Type os.environ['PYTHONPATH'].split(os.pathsep) and press Enter.
When you have a PYTHONPATH environment variable defined, you see a list of paths, as shown in the figure below. However, if you don’t have the environment variable defined, you see an error message instead.
The sys.path attribute doesn’t include the split() function, which is why the example uses a for loop with it. However, the os.environ['PYTHONPATH'] attribute does include the split() function, so you can use it to create a list of individual paths.
You must provide split() with a value to look for in splitting a list of items. The os.pathsep constant (a variable that has one, unchangeable, defined value) defines the path separator for the current platform so that you can use the same code on any platform that supports Python.
When you list the sys.path contents again, you see that the new entry is added to the end of the list. Likewise, when you want to remove an entry you type sys.path.remove(os.getcwd()) and press Enter. The addition is present only during the current session.