2

I know there are already a lot of questions similar to this one but unfortunately I haven't found out how to apply to my problem.

The structure of my project is as follows:

Project
|___ maincode
      |___ __init__.py
      |___ losses.py
      |___ bin
           |___ __init__.py
           |___ train.py

and then in train.py I have the following code:

# Allow relative imports when being executed as script.
if __name__ == "__main__" and __package__ is None:
    __package__ = "maincode.bin"
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))

    from .. import losses

def main(args=None):
    #some code here

if __name__ == '__main__':
    main()

Now if I execute the script train.py from the project main directory Project/, i.e. running the following in the terminal:

maincode/bin/train.py

then I obtain the following error:

SystemError: Parent module 'maincode.bin' not loaded, cannot perform relative import

I tried both with Python 2.7.6 and Python 3.5.2 and obtained the same error.

Could you please help? Thank you in advance!

f10w
  • 1,524
  • 4
  • 24
  • 39

2 Answers2

4

If you just want to run that module and not the whole Package. Do python -m maincode.bin.train which tells python to run it as a module.

If you want to run the whole package then change directory into the Project: cd /path/to/project then run: python maincode and if your code is set up correctly it should run train.py.

Otherwise, move the script outside of the Package and run it on it's own.

More on this and understanding Packages can be found here: Relative imports for the billionth time

edlee
  • 665
  • 1
  • 7
  • 20
0

Files in the same directory can only use the "import module" and cannot use the "from" keyword, for unknown reasons

LWX
  • 37
  • 6