imports custom module python

2019-08-15 20:09发布

问题:

I have a file I.py and X.py both are custom modules

I'm trying to do an import from X.py file like:

from myapp.I import Int

But, when I try to run in shell, it throws an import error of:

ImportError: No module named myapp.I

X.py is in a subdir of I.py

X.py is in: myapp/a/x.py
I.py is in: myapp/

what am I doing wrong? Sorry this is slightly basic, it seems so trivial, but I can't seem to get it to work.

Thank you.

回答1:

You're going to need an __init__.py within myapp/ and myapp/a/. See What is __init__.py for? for more details.



回答2:

You can't execute X.py directly, even with the required __init__.py files (have you added those?)

This is a limitation (or feature, depending on how you see it). To get around it, you need to create a simple runner script of sorts in the top-level directory which then imports X and executes it.