Modifying the Python Path Permanently with PYTHONPATH
While modifying sys.path within a script is useful for temporary changes, you might want to add a directory to the Python path for all your Python sessions or for a specific project without modifying individual scripts. This can be achieved by setting the PYTHONPATH environment variable.
The PYTHONPATH environment variable is a list of directories that Python adds to sys.path when it starts.
To set the PYTHONPATH environment variable for your current terminal session, you can use the export command.
Let's remove the sys.path.append() line from use_custom_module.py and use PYTHONPATH instead.
Open use_custom_module.py in the WebIDE editor and remove the following lines:
## Get the absolute path to the custom modules directory
custom_modules_path = os.path.join(os.path.dirname(__file__), 'my_custom_modules')
## Add the custom modules directory to sys.path
sys.path.append(custom_modules_path)
The use_custom_module.py file should now look like this:
import sys
import os
## Now you can import my_module
import my_module
message = my_module.greet("LabEx User")
print(message)
## Optional: Print sys.path again to see the added directory
print("\nUpdated sys.path:")
print(sys.path)
Save the file.
Now, try running the script without setting PYTHONPATH:
python use_custom_module.py
You will likely get an ModuleNotFoundError because Python cannot find my_module.
Traceback (most recent call last):
File "/home/labex/project/use_custom_module.py", line 5, in <module>
import my_module
ModuleNotFoundError: No module named 'my_module'
Now, let's set the PYTHONPATH environment variable in the terminal to include our custom modules directory. Make sure you are in the /home/labex/project directory.
export PYTHONPATH="/home/labex/project/my_custom_modules:$PYTHONPATH"
This command adds /home/labex/project/my_custom_modules to the beginning of the PYTHONPATH variable. The $PYTHONPATH at the end ensures that any existing directories in PYTHONPATH are preserved.
Now, run the use_custom_module.py script again in the same terminal session:
python use_custom_module.py
You should see the output indicating that the module was found and executed:
Hello, LabEx User from my_module!
Updated sys.path:
['/home/labex/project', '/home/labex/project/my_custom_modules', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/labex/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']
Notice that /home/labex/project/my_custom_modules is now included in sys.path because we set the PYTHONPATH environment variable.
Setting PYTHONPATH in the terminal using export only affects the current terminal session. To make the change permanent, you would typically add the export command to your shell's startup file (e.g., ~/.bashrc, ~/.zshrc). However, for this lab, setting it in the current session is sufficient to demonstrate the concept.