RocketTwitch
RocketTwitch

Reputation: 295

Python Import Module on Raspberry Pi

I know this has been asked dozens of times but I can't see what in the world I'm doing wrong. I'm trying to import a module in python 2.7 from a different directory. I would greatly appreciate some input to help me understand why this method doesn't work. I have the following directory structure on my raspbian system:

/home/pi/
        ...projects/__init__.py
        ...projects/humid_temp.py

        ...python_utilities/__init.py__
        ...python_utilities/tools.py

I'm calling humid_temp.py and I need to import a function within tools.py This is what their contents look like:

humid_temp.py:

import os
import sys
sys.path.append('home/pi/python_utilities')
print sys.path
from python_utilities.tools import *

tools.py:

def tail(file):
    #function contents
    return stuff

The print sys.path output contains /home/pi/python_utilities

I'm not messing up my __init__.py's am I? I've also ruled out possible permission issues with that path as I gave it full 777 access and I still hit the

ImportError: No module named python_utilities.tools.

What did I miss?

Upvotes: 1

Views: 4745

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 91009

When you want to import something like -

from python_utilities.tools import *

You need to add the parent directory of python_utilities to sys.path , not python_utilities itself. So, you should add something like -

sys.path.append('/home/pi')       #Assuming the missing of `/` at start was not a copy/paste mistake

Also, just a note, from <module> import * is bad , you should consider only importing the required items, you can check the question - Why is "import *" bad? - for more details.

Upvotes: 2

lipponen
lipponen

Reputation: 753

In humid_temp.py, just write:

from python_utilities import tools

There is no need for appending subfolder to sys.path.

Then when you want to use functions from tools, just

tools.function()

Upvotes: 2

Related Questions