[英]Python cannot find module from command line but works from eclipse
I am very new to Python and have strange error. 我是Python的新手,并且遇到奇怪的错误。 I am using Eclipse/PyDev for development and Python 2.7.3 in eclipse and commandline.
我正在使用Eclipse / PyDev进行开发,并在Eclipse和命令行中使用了Python 2.7.3。 I created several modules, every folder has init .py file and other source files.
我创建了几个模块,每个文件夹都有init .py文件和其他源文件。 When I try to execute file with
__name__ == '__main__'
from eclipse it works fine but from command line when I call like 当我尝试从Eclipse用
__name__ == '__main__'
执行文件时,它工作正常,但是从命令行调用时就像
python models.py
Traceback (most recent call last):
File "models.py", line 8, in <module>
from database import uuid_generator
ImportError: No module named database
it looks like 看起来像
Can anybody give me clue what can be problem ?
有人可以告诉我什么可能是问题吗?
database
parent directory is not in sys.path
(pythonpath). database
父目录不在sys.path
(pythonpath)中。 Try to run the script as python -mdatabase.uuid_generator
while in the parent (toplevel) directory. 尝试在父(顶级)目录中以
python -mdatabase.uuid_generator
身份运行脚本。 Or create a wrapper script: 或创建包装器脚本:
from database.uuid_generator import main
main()
And put it in database
's parent (toplevel) directory. 并将其放在
database
的父(顶层)目录中。 When you call this script its directory is added to sys.path
automatically so everything works without modifying modules inside database
directory or PYTHONPATH
environment variable. 当您调用此脚本时,其目录会自动添加到
sys.path
因此无需修改database
目录或PYTHONPATH
环境变量中的模块,一切都可以正常工作。
Only the toplevel directory that has no __init__.py
in it (not a Python package) need to be in sys.path
ie, database
directory should not be in sys.path
. 只有其中没有
__init__.py
的顶级目录(不是Python包)才需要位于sys.path
即database
目录不应位于sys.path
。
See Traps for the unwary . 请参阅陷阱以防不慎 。
Try using this instead 尝试改用这个
from uuid_generator
edit: make sure uuid_generator.py is in the same folder as models.py 编辑:确保uuid_generator.py与models.py位于同一文件夹中
Apparently eclipse has added the database directory to the module search path. 显然eclipse已将数据库目录添加到模块搜索路径。
To get the same effect without modifying the script you can append the path to database into $PYTHONPATH environment variable. 要获得相同的效果而无需修改脚本,可以将数据库的路径附加到$ PYTHONPATH环境变量中。
If you are open to modifying the script you can add this towards the top after importing relevant modules sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
如果您愿意修改脚本,可以在导入相关模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
之后将其添加到顶部。
untested hack 未经测试的黑客
see JFSebastian's answer and comment below instead 请参阅下面的JFSebastian的答案和评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.