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.


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


import sys

for p in sys.path:
print p

Then call it from your command line:

root@raspberrypi:~# python path.py

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

import RPi.GPIO as GPIO


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
find: ‘/usr/lib/python2.7/lib-old’: No such file or directory

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


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 )

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

%d bloggers like this: