简体   繁体   中英

ImportError: No module named modules.TestModule

I have been stuck in this issue for a long time, my project structure goes like this,

在此处输入图片说明

import web
import sys
sys.path.append("...")
import modules.TestModule as TM    
urls = (
    '/testmethod(.*)', 'TestMethod'
)    
app = web.application(urls, globals())   
class TestMethod(web.storage):
    def GET(self, r):    
        return TM.get_func(web.input().string)    
if __name__ == "__main__":
    app.run()

When I execute the TestService.py it says "ImportError: No module named modules.TestModule Python"

This is a sample made to test the module .

What is the entry point for your program? Usually the entry point for a program will be at the root of the project. Since it is at the root, all the modules within the root will be importable. But in your case entry point itself is a level inside the root level.

The best way should be have a loader file (main.py) at root level and rest can be in packages. The other non-recommended way is to append root directory path in sys.path before importing any package.

Add below code before you import your package.

import os, sys
currDir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.abspath(os.path.join(currDir, '..'))
if rootDir not in sys.path: # add parent dir to paths
    sys.path.append(rootDir)

I have modified yut testscript.py code as below. Please try it out.

import web
import sys
import os, sys
    currDir = os.path.dirname(os.path.realpath(__file__))
    rootDir = os.path.abspath(os.path.join(currDir, '..'))
    if rootDir not in sys.path: # add parent dir to paths
        sys.path.append(rootDir)

import modules.TestModule as TM    
urls = (
    '/testmethod(.*)', 'TestMethod'
)    
app = web.application(urls, globals())   
class TestMethod(web.storage):
    def GET(self, r):    
        return TM.get_func(web.input().string)    
if __name__ == "__main__":
    app.run()

If the directory 'DiginQ' is on your python sys.path, I believe your import statement should work fine.

There are many ways to get the directory 'DiginQ' on your python path.

Maybe the easiest (but not the best) is to add a statement like this before you import modules.Testmodule:

import sys
sys.path.extend([r'C:\Python27\DiginQ'])

Based on your post it looks like the path is C:\\Python27\\DiginQ but if that's not correct just use the right path.

If you google how to set python path you will find many hits. Most important thing is your path has to include the directory above the directory with the package you are attempting to import. In your case, that means DiginQ.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM