arpit joshi arpit joshi - 6 days ago 6
Python Question

Running python from command line gives import error

I want to run my python program from command line but it gives me below error

ImportError: No module named 'main'


My folder structure is as below

Project

|-----main

|-----__init__.py

|-----S3Operations.py

|-----BusinessOperations.py


My init.py code is as below

import sys
from S3Operations import Models
sys.path.append("D:/code/Project/main")
if __name__ == '__main__':
s3=Models()
s3.test()


And my S3Operations.py code is

import os.path
from main import BusinessService

class ModelsMlS3(object):

def test(self):
print("Testing success")


When I run the program using command line i get the below error

$ python __init__.py
Traceback (most recent call last):
File "__init__.py", line 2, in <module>
from S3Operations import ModelsMlS3
File "D:\code\Project\main\S3Operations.py", line 11, in <module>
from main import BusinessService
ImportError: No module named 'main'


Can any one please suggest a solution for the same.

Answer

You just need to do:

import BusinessService  # instead of `from main import BusinessService`

as in your project, there is no __init__.py file present in Project directory (which holds main.py).

For importing it like:

from main import BusinessService

you need to create __init__.py in the folder in order to make it as module.