Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set your python path on Linux?
To set the PYTHONPATH on Linux to point Python to look in other directories for the module and package imports, you can use the export command. This is useful when you have custom modules or packages in non-standard locations.
Setting PYTHONPATH Temporarily
To add a directory to PYTHONPATH for the current terminal session ?
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
This command appends the foo directory to the existing PYTHONPATH without replacing its original value.
Example
Let's create a custom module and add its directory to PYTHONPATH ?
$ mkdir ~/mymodules
$ echo "def greet(): return 'Hello from custom module!'" > ~/mymodules/custom.py
$ export PYTHONPATH=${PYTHONPATH}:~/mymodules
$ python3 -c "import custom; print(custom.greet())"
Hello from custom module!
Setting PYTHONPATH Permanently
To make the change permanent, add the export command to your shell configuration file ?
# Add to ~/.bashrc or ~/.zshrc
echo 'export PYTHONPATH=${PYTHONPATH}:${HOME}/mymodules' >> ~/.bashrc
source ~/.bashrc
Checking Current PYTHONPATH
You can verify your PYTHONPATH setting using these methods ?
import sys
print("Python path directories:")
for path in sys.path:
print(path)
Or from the command line ?
$ echo $PYTHONPATH
Best Practices
In most cases, you shouldn't modify PYTHONPATH. Consider these alternatives:
- Use virtual environments with
pip install -e .for development - Install packages properly using
pip install - Use sys.path.append() within your Python script for temporary additions
Alternative: Using sys.path
import sys
sys.path.append('/home/user/mymodules')
import custom
print(custom.greet())
Conclusion
While PYTHONPATH can be useful for custom module locations, it's often better to use virtual environments or proper package installation. Use PYTHONPATH sparingly and prefer more maintainable solutions.
