简体   繁体   中英

Importing local python module from directory with __init__.py

I have been working on a project that requires editing and using an opensource project, lets call it osproj. I renamed the folder containing the edited scripts to osprojmine.

Here is an example directory structure:

root/  
    mycode.py  
    osprojmine/  
        __init__.py  
        foo.py  
        bar.py  

In mycode.py I have the import statement

import osprojmine as osproj

I have been able to use osproj.module() and osproj.class() within mycode.py with no issues and everything runs smoothly on my end.

The issue arises when I send the files over to my colleague. He is getting a
ModuleNotFoundError: No module named 'osprojmine'

I am using python 3.8.5. He was on 3.9.6 and has tried downgrading.

It seems his python interpreter just isn't recognizing osprojmine as a python package but on my end it does? Very confused. I am relatively new to this field so any and all advice welcome!

The colleague (and you for that matter) should run the code as:

$ cd root
$ python -m mycode

This way the absolute import will be resolved

When you import a module, python perform lookup in directories specified in sys.path to find either a module.py or module/__init__.py file.

By default, after startup sys.path contains:

  • Current directory ( "" )
  • Directories specified by PYTHONPATH
  • Python builtin paths
  • Local site-package specified by PYTHONUSERBASE
  • System site-package (or virtualenv site-package)

You cannot import osprojmine because the root directory does not meet any of these conditions.

In a first time you can:

  • Run python from root directory
  • Add root directory to your PYTHONPATH , permanently or temporary:
     env PYTHONPATH=/path/to/root:${PYTHONPATH} python ...

But that's poor man's solution, best is to package your project with setuptools and install it (evently in development mode ) either in local site-pakage, named user scheme , or in virtualenv site-package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM