I'v been struggling with importing a sub module. In main.py two modules are imported located under 220_04_070. I'm using importlib since the directory name only consist of numbers. common.py just contains a number of variables.
The problem I get is:
.../220_04_070/unicorn.py", line 1, in <module>
from common import *
ModuleNotFoundError: No module named 'common'.
I can get around by adding a dot in front of common in unicorn.py. But since unicorn is used standalone at other parts I prefer not to do that.
from mon import *
Both main.py and unicorn.py are using common.py. The structure is as below:
|-- main.py
|
|-- 220_04_070
|-- common.py
|-- unicorn.py
main.py
import importlib
uc = importlib.import_module('220_04_070.unicorn')
cm = importlib.import_module('220_04_070mon')
mycorn = uc.unicorn()
unicorn.py
from common import *
class unicorn():
def __init__(self):
None
All is run with python3.12.3 (Ubuntu 24.04).
So, my question is how I should handle this?
I'v been struggling with importing a sub module. In main.py two modules are imported located under 220_04_070. I'm using importlib since the directory name only consist of numbers. common.py just contains a number of variables.
The problem I get is:
.../220_04_070/unicorn.py", line 1, in <module>
from common import *
ModuleNotFoundError: No module named 'common'.
I can get around by adding a dot in front of common in unicorn.py. But since unicorn is used standalone at other parts I prefer not to do that.
from mon import *
Both main.py and unicorn.py are using common.py. The structure is as below:
|-- main.py
|
|-- 220_04_070
|-- common.py
|-- unicorn.py
main.py
import importlib
uc = importlib.import_module('220_04_070.unicorn')
cm = importlib.import_module('220_04_070mon')
mycorn = uc.unicorn()
unicorn.py
from common import *
class unicorn():
def __init__(self):
None
All is run with python3.12.3 (Ubuntu 24.04).
So, my question is how I should handle this?
Share Improve this question asked Feb 11 at 12:37 hzcodechzcodec 571 gold badge1 silver badge4 bronze badges 4 |1 Answer
Reset to default 0I manage to get it running. I have a solution, however maybe there is another way.
I change my common.py file to:
import importlib
#check if it's run from above or from local main()
if __name__ == '__main__':
common = importlib.import_module('common')
else:
common = importlib.import_module('220_04_070mon')
class unicorn:
def __init__(self):
None
def get_data(self):
print("var: ", common.VAR1)
def main():
mycorn = unicorn()
if __name__ == '__main__':
main()
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745211595a4616873.html
__init__.py
or__main__.py
? Are you creating a package that will later be installed with pip? – Markus Hirsimäki Commented Feb 11 at 17:31