0

I got a problem with python projects. Here is my directory like:

Hotel/
    hotel/__init__.py
          a.py
          b.py
          c.py
    bin/run.py
    README

The whole idea is that I want to write a package hotel, and then I'll write some scripts(run.py) to use that package. So I put

from hotel import a

in to the file run.py.

But however, when I tried to run the run.py file under the directory Hotel with the command:

python ./bin/run.py

There is an import error saying: no module named hotel. But when I use ipython under this directory and when I type

from hotel import a

it works well. I don't know when I am wrong. Could anyone help me?

Elona Mishmika
  • 480
  • 2
  • 5
  • 21

2 Answers2

0

As outlined in this answer, it does not matter from where you run run.py, it will be the scripts directory that will be added to the PYTHONPATH.

In python2.7 you will run into problems in any case if you do not put __init__.py files in the Hotel folder as well as the bin folder because you will not be able to execute them should you place the Hotel folder somewhere on your machine's PYTHONPATH.

You have two choices:

1) Put the package on the PYTHONPATH manually:

bin/run.py:

import sys
sys.path.insert(0,'..')
from hotel import a

2) Move out run.py to the parent directory:

Hotel/
    __init__.py  
    hotel/__init__.py
          a.py
          b.py
          c.py
    run.py
    README
Community
  • 1
  • 1
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • Thanks, for method 1 I think it's OK, for method 2 I have never seen people do like this, in every github repository there is no .py in the project folder.. – Elona Mishmika Oct 22 '15 at 15:27
0

So hotel is a module for you. In order to be able to import it, you have to have the following in your python path: .../Hotel where ... is the full path to your Hotel directory. Try import sys; print sys.path to check it out.

gplayer
  • 1,741
  • 1
  • 14
  • 15