[英]cannot import a python module from a python package
I have this repository structure:我有这个存储库结构:
py_files_and_packages/ # normal folder
package/
module1.py # contains a class
module2.py
the __init__.py
file of this package contains only __author__='my name'
这个包的
__init__.py
文件只包含__author__='my name'
The Problem:问题:
I am trying to import the class from module1.py into model2.py.我正在尝试将该类从 module1.py 导入到 model2.py 中。 When I use
当我使用
from package.model1 import model1
and rung the script(model2.py) within PyCharm it works.并在 PyCharm 中运行脚本(model2.py)它可以工作。 However, when I run it from the command line it doesn't find the package.
但是,当我从命令行运行它时,它找不到包。 The error message:
ImportError: No module named 'my package's name'
.错误消息:
ImportError: No module named 'my package's name'
。
I tried many tricks I found on the web such as ( https://stackoverflow.com/a/22777011/2804070)but it didn't work.我尝试了很多在网上找到的技巧,例如( https://stackoverflow.com/a/22777011/2804070) ,但没有奏效。
I am using python-3.5.1 (installed locally), PyCharm 5.0.4 community edition, OS debian wheezy我使用的是 python-3.5.1(本地安装),PyCharm 5.0.4 社区版,操作系统 debian wheezy
the problom is that python can't find your package, because it is not in search path.问题是python找不到您的包,因为它不在搜索路径中。
in model2.py, try to add the following before from package.model1 import model1
在model2.py中,尝试在
from package.model1 import model1
model1之前添加以下内容
import sys
sys.path.append('/path/to/py_files_and_packages')
so it looks like this:所以它看起来像这样:
import sys
sys.path.append('/path/to/py_files_and_packages')
from package.model1 import model1
# your code here
在model2.py
试试这个:
from module1 import your_class_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.