How to set Python environment variable PYTHONPATH on Linux?

The PYTHONPATH environment variable tells Python where to look for modules and packages beyond the standard library. Setting it correctly on Linux ensures your custom modules can be imported from any location.

Basic PYTHONPATH Setup

Open a terminal and use the export command to set PYTHONPATH ?

export PYTHONPATH=/home/user/myproject:$PYTHONPATH

This command adds /home/user/myproject to PYTHONPATH while preserving any existing paths. The colon (:) separates multiple paths on Linux.

Verifying PYTHONPATH

Check if PYTHONPATH was set correctly ?

echo $PYTHONPATH

This displays the current PYTHONPATH value, showing all directories Python will search for modules.

Common PYTHONPATH Examples

Single Path

export PYTHONPATH=/path/to/your/python/module

Multiple Paths

export PYTHONPATH=/path/to/first/module:/path/to/second/module

Including Current Directory

export PYTHONPATH=.:$PYTHONPATH

Path with Spaces

export PYTHONPATH="$PYTHONPATH:/path/with spaces/my_module"

Making PYTHONPATH Permanent

The export command only affects the current terminal session. For permanent setup, add the export command to your shell configuration file ?

echo 'export PYTHONPATH=$PYTHONPATH:~/my_module' >> ~/.bashrc
source ~/.bashrc

This appends the PYTHONPATH setting to .bashrc and reloads the configuration.

Testing Your Module Import

After setting PYTHONPATH, verify your module can be imported ?

import sys
print("Python search paths:")
for path in sys.path:
    print(path)
Python search paths:
/usr/lib/python3.x/site-packages
/home/user/myproject
...

Best Practices

Scenario Command Use Case
Development export PYTHONPATH=.:$PYTHONPATH Include current directory
Project-specific export PYTHONPATH=/project/path:$PYTHONPATH Add project modules
Multiple projects export PYTHONPATH=/path1:/path2:$PYTHONPATH Multiple module locations

Conclusion

Use export PYTHONPATH to add custom module paths on Linux. Add the export command to ~/.bashrc for permanent configuration. Always append to existing PYTHONPATH using $PYTHONPATH to preserve system paths.

Updated on: 2026-03-24T16:57:01+05:30

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements