Exposing Python’s Module Search Path!

I recently bought a Raspberry Pi and started getting my hands dirty with Python (again).

The project I copied was very simple and all it did was make an LED blink.

But one line from the program puzzled me:

import RPi.GPIO as GPIO

So naturally, once I got confused, I started to get curious…the programmer in me asked:

  • What is that line actually doing (beside obviously importing a Python module)?
  • What does the code from that module actually look like?
  • Which directories did Python actually search to find the module?

Knowing this will allow me to dig a little deeper with programming, Python, and Raspberry Pi.

Especially when I start developing my own projects from scratch to build my multi-million dollar solution 🤑 But I digress.

THE CODE

Go a head and copy the following code into path.py:

#!/usr/bin/python

import sys

for p in sys.path:
print p

Then call it from your command line:

root@raspberrypi:~# python path.py
/root
/usr/lib/python2.7
/usr/lib/python2.7/plat-arm-linux-gnueabihf
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages

The above output shows us every single directory Python searched when it hit the line:

import RPi.GPIO as GPIO

NOW, IT GETS EVEN BETTER!

We can take this a step further and see every Python module we have available to us:

root@raspberrypi:~# python path.py | xargs -n1 -I {} find {} -name "*.py"

Now, we can search for the module I was curious about in the beginning:

root@raspberrypi:~# python path.py | xargs -n1 -I {} find {} -name "*.py" | grep RPi.GPIO
/usr/lib/python2.7/dist-packages/RPi/GPIO/__init__.py
/usr/lib/python2.7/dist-packages/RPi/__init__.py
find: ‘/usr/lib/python2.7/lib-old’: No such file or directory
/usr/lib/python2.7/dist-packages/RPi/GPIO/__init__.py
/usr/lib/python2.7/dist-packages/RPi/__init__.py

Not to mention, we have a pretty good troubleshooting technique as well.

QUICK DEMONSTRATION BELOW

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s