How to import modules from different folders? I have the following
cgi-bin
| py
|
__init.py__
http
|
__init.py__
HttpFormParser.py
xml
|
__init.py__
XmlDocumentCreator.py
I want to import XmlDocumentCreator in HttpFormParser.py. How to do that ?
I'm doing
import py.xml.XmlDocumentCreator
in HttpFormParser.py and its throwing the following error.
/HttpFormParser.py", line 5, in <module>
import py.xml.XmlDocumentCreator
ImportError: No module named py.xml.XmlDocumentCreator
-
1possible duplicate of Python package structureire_and_curses– ire_and_curses2011年05月25日 23:09:55 +00:00Commented May 25, 2011 at 23:09
2 Answers 2
Just work out the directory you're executing from, as told by sys.argv[0]. In this case, you want to get the cgi-bin directory since it contains py:
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir, os.pardir)))
import py.xml.XmlDocumentCreator
P.S. if you're using WSGI, you don't need your Python code in a cgi-bin directory, where it could be downloaded if your .htaccess (or equivalent) is set wrong.
Comments
Did you try:
from ..xml import XmlDocumentCreator
?
Generally I encourage you to read sections The Module Search Path and Intra-package References @ http://docs.python.org/tutorial/modules.html