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:
then I obtain the following error:<blockquote>
SystemError: Parent module 'maincode.bin' not loaded, cannot perform relative import</blockquote>
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!Answer1:
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: <a href="https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time" rel="nofollow">Relative imports for the billionth time</a>Answer2:
Files in the same directory can only use the "import module" and cannot use the "from" keyword, for unknown reasons