简体   繁体   中英

How to import submodules from relative path?

I have multiple modules in my project and specify some execution point. But when I try to import files from submodules, it doesn't work.

So, how to specify submodules to execute from selected execution file?

project
--bin
---- executeFile
--modules
---- __init__.py
----fileA.py

in executeFile , I try:

from ..modules.fileA import * 

but get the error:

Traceback (most recent call last):
File "./bin/muexecute", line 10, in <module>
  from ..modules.os import *
SystemError: Parent module '' not loaded, cannot perform relative import

I found solution. The problem was in my opinion about using init .py. I placed in executable scripts path to including and it works fine

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

All modules you want to import should in in your PYTHONPATH. Therefore there is no hierarchy. In your case It seems to me that an __init__.py is missing from your project's main folder (with all the models included), so executefile doesn't know about your modules.

So you are having trouble defining your relative path, correct? Try the following:

from sys import path
path.append('C:\\realative_path')
from function_file import required_function

Hope that helps.

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