1

I am aware that __init__.py is needed for imports and to make python treat folder as package.

Below is my directory structure

init_stuffs/
├── __init__.py
├── __init__.pyc
└── new_pack
    ├── __init__.py
    ├── __init__.pyc
    ├── animal.py
    ├── animal.pyc
    ├── bird.py
    ├── bird.pyc
    └── common.py

When i cd in the directory and try to run my common.py i get below error

(robo-fm) ~/Desktop/python_code/init_stuffs/new_pack $ python common.py
Traceback (most recent call last):
  File "common.py", line 6, in <module>
    from new_pack import xinit
ImportError: No module named new_pack

but below works fine :

(robo-fm) ~/Desktop/python_code/init_stuffs $ python -m new_pack.common

 i am a bird class

 i am a bird

 i am in animal class

 i am a lion

 i am a bird class

 i am a bird

 i am in animal class

 i am a lion
('x=', 5)

checked this thread as well ImportError: No module named package, but no help

common.py

import sys
# import os
# sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))

# print sys.path
from new_pack import xinit 
from bird import bird 
from animal import animal 

x=bird()
x.sparrow()
y=animal()
y.lion()
print("x=",xinit)

__init__.py

# print("\n hi i am __init__")
xinit=5

I am on python2.7

Question

how can i run common.py as file rather than running it as part of module using -m?

TIA

ontheroad
  • 31
  • 1

0 Answers0