Reputation: 33
Here's my folder structure:
main.py
tools/
sub1.py
sub2.py
where main.py:
import tools.sub1
import tools.sub2
and sub1.py:
a = 'abc'
and sub2.py (directly import sub1 is not working, is it because I am running main.py from the root directory?):
import tools.sub1
print(tools.sub1)
from here, I knew that in order to correctly call sub1, sub2 from main, we have to add the statement import tools.sub1 in sub2, however, if I want to run sub2 individually, error occurs
Traceback (most recent call last):
File "sub2.py", line 1, in <module>
import tools.sub1 as sub1
ModuleNotFoundError: No module named 'tools'
So, My question is that is it possible to directly run sub2 individually, while keeping the current design that we can properly run main.py?. Thanks in advance.
Upvotes: 2
Views: 46
Reputation: 494
You can do this by making tools
a python module. Adding an __init__.py
file (can be empty) in your tools directory will make Python consider the "tools" folder a module. You can then reference sub1
from both main.py
and sub2.py
with:
from tools import sub1
Upvotes: 1
Reputation: 96
You can run sub2 using python -m tools.sub2
More info on using -m https://docs.python.org/3/using/cmdline.html#cmdoption-m
Upvotes: 1