我的文件是这样的
w3school:
spiders
__ __init___.py
w3school_spider.py
__init__.py
items.py
我现在在w3school_spider.py中导入items中的一个类,我写的是这样:
from w3school.items import W3schoolItem
但是显示
ImportError: No module named w3school.items
如果我改成:
from .items import W3schoolItem
则会显示:
ValueError: Attempted relative import in non-package
我搜了一下是不是路径问题?需要我把这个items.py放进c/python2.7/lib中吗?
请各位看看,谢谢。
The command line parameter -m can start the module in a modular manner. At this time, the name is the module name (not __main__), and relative import can be added to the program.
The -m operation must be executed in the directory above the module (not in the current directory) , format: python -m new.w3school_spider
Remember there is no .py at the end.
You can also put items.py directly into spiders. At this time, items.py and w3school_spider.py are in the same
folder. By default, relative import is performed, directly from items import W3schoolItem
The first error is because Python did not find the module you want in the same file. The second error is because the running module
(named __main__) cannot have relative imports.
Try adding
in frontAnd the relative path is relative to the current module name, and the main module name must be "__main__", so
the package with the relative path cannot be found in the main module, and the absolute path must be used. Relative paths can only be used for non-main modules
w3school
spiders
__init__.py
w3school_spider.py
__init__.py
items.py
Is your directory structure like this, and then reference the content in items.py in w3school_spider.py?
This should do the trick.
In a package, peers use
.
,父级使用..
.Finally, there is a suggestion, you can put some commonly used classes or functions in a package into __init__.py.