[英]Python unable to import custom module despite having __init__.py
I have a folder with a __init__.py
我有一个带有
__init__.py
的文件夹
File __init__.py:文件 __init__.py:
#!/usr/bin/python2
flags="test"
File main.py:文件main.py:
#!/usr/bin/python2
import foldername
def main():
print foldername.flags
if __name__ == '__main__':
main()
Now, when I run ./main.py
(from inside the folder), I get the error现在,当我运行
./main.py
(从文件夹内部)时,我收到错误
ImportError: No module named foldername
Run from the parent folder for foldername
:从文件夹
foldername
的父文件夹运行:
$ python -m foldername.main
If you rename main.py
to __main__.py
then you could run it as (since Python 2.7):如果您将
main.py
重命名为__main__.py
那么您可以将其运行为(自 Python 2.7 起):
$ python -m foldername
python -m
adds implicitly current directory to your python path ( sys.path
). python -m
将当前目录隐式添加到您的 python 路径( sys.path
)。
Parent Folder/
└── foldername
├── __init__.py
│ # flags="test"
└── __main__.py
# import foldername
#
# def main():
# print foldername.flags
#
# if __name__=="__main__":
# main()
If the parent directory for foldername
is in your python path then you could run the above commands from any directory.如果文件
foldername
的父目录在您的 python 路径中,那么您可以从任何目录运行上述命令。
PYTHONPATH issue. PYTHONPATH问题。 Make sure that "foldername" is available in your path.
确保“文件夹名”在您的路径中可用。 If you are running it from inside "foldername" it might not be available.
如果您从“文件夹名”内部运行它,它可能不可用。 Try running from the parent of "foldername".
尝试从“文件夹名”的父级运行。
Here is a question about finding your PYTHONPATH .这是一个关于找到你的 PYTHONPATH 的问题。
Make sure your layout is like this:确保您的布局是这样的:
./folder/__init__.py
./main.py
and there is not file named folder.py
!并且没有名为
folder.py
文件!
Change to the parent folder, so that ls folder/__init__.py
works.更改到父文件夹,以便
ls folder/__init__.py
工作。
Next try running python -c "import folder"
.接下来尝试运行
python -c "import folder"
。
If you want to import the a module in python3 simply go to the root folder如果要在 python3 中导入模块,只需转到根文件夹
python3 -mModuleName
Make sure you do not remove the -m
before the module name and then this you can import this module anywhere inside the project directory.确保您没有删除模块名称之前的
-m
,然后您可以在项目目录中的任何位置导入此模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.