Ad

I Can't Import A File But The Other File In The Folder Can

- 1 answer

Since Yesterday, i have a problem with import.
I do not understand how the import of the code I need to edit work.

The config.py is in the root folder of the project and the server is launched here.

In server/src/session.py, we can found this

#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# vim:set ft=python ts=4 sw=4 sts=4 autoindent:

'''docstring'''

from __future__ import with_statement

from Cookie import CookieError, SimpleCookie
from atexit import register as atexit_register
from datetime import datetime, timedelta
from hashlib import sha224
from os import makedirs, remove
from os.path import exists, dirname, join as path_join, isfile
from shutil import copy
from shutil import move
from tempfile import mkstemp

try:
    from cPickle import dump as pickle_dump, load as pickle_load
except ImportError:
    from pickle import dump as pickle_dump, load as pickle_load

from config import WORK_DIR

The last import is weird, because there is no server/src/config.py, the config.py file is in the root of project folder.
So, why he can import config here ?

when i try doing the same thing in my file server/src/save_in_database.py :

import MySQLdb
import os
from config import DB_HOST, DB_USER, DB_PASS

i got an import error :

Traceback (most recent call last):
  File "server/src/save_in_database.py", line 4, in <module>
    from config import DB_HOST, DB_USER, DB_PASS
ImportError: No module named config

And when i try to import session file in my file server/src/save_in_database.py, i got an error but in other file it's work perfectly.

Traceback (most recent call last):
  File "server/src/save_in_database.py", line 3, in <module>
    from session import get_session
  File "/home/etienne/ed-labelisator/back/server/src/session.py", line 32, in <module>
    from config import WORK_DIR
ImportError: No module named config

I do not understand how the original programmer to import, if someone can help me.
Thank you and sorry for the bad english

Ad

Answer

Ok, after several research, I solved my problem.

when i launch the server, the program add src/server to the python path:

sys.path.append(os.path.join(os.path.dirname(__file__), 'server/src'))

So, the . AND ./src/server can be imported, it's why it's work for him.


And me, when i do python2 server/src/save_in_database.py, the . directory is not added to the python pah, so i can't import config and the other file can't do that either.

For fix this, i added this following code to the server/src/save_in_database.py

if __name__ == '__main__':
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
Ad
source: stackoverflow.com
Ad