[英]how to import python file from another directory
I am working on a django rest framework and can't import .py files from another directory.我正在开发 django rest 框架,无法从另一个目录导入 .py 文件。 I have
__init__.py
files included in the directory:我在目录中包含
__init__.py
文件:
├── admin.py
├── apps.py
├── heroes
│ ├── __init__.py
│ ├── models.py
│ ├── __pycache__
│ │ └── views.cpython-38.pyc
│ ├── serializers.py
│ └── views.py
├── __init__.py
├── migrations
│ ├── __init__.py
│ └── __pycache__
│ └── __init__.cpython-38.pyc
├── models.py
├── __pycache__
│ ├── admin.cpython-38.pyc
│ ├── apps.cpython-38.pyc
│ ├── __init__.cpython-38.pyc
│ ├── models.cpython-38.pyc
│ └── urls.cpython-38.pyc
├── tests.py
├── urls.py
├── views.py
└── villians
├── __init__.py
├── models.py
├── serializers.py
└── views.py
I want to import heroes/views.py
to base urls.py
我想导入
heroes/views.py
到 base urls.py
please check if you use a proper import statement.请检查您是否使用了正确的导入语句。 In python you define separate subfolders via
.
在 python 中,您通过
.
, do not use a /
. ,不要使用
/
。
Just run a test successfully on my system, Python 3.8.6 .只需在我的系统Python 3.8.6上成功运行测试即可。
Fs-structure: Fs-结构:
./urls.py
./heroes
./heroes/__init__.py
./heroes/views.py
heroes/views.py英雄/views.py
#!/usr/bin/python
def say_hello():
print('Hello from {}'.format(__file__))
urls.py网址.py
#!/usr/bin/python
from heroes.views import say_hello
# import everything
# from heroes.views import *
if __name__ == "__main__":
print('Hello from {}'.format(__file__))
say_hello()
or if you prefer this method:或者如果您更喜欢这种方法:
import heroes.views as submod
if __name__ == "__main__":
print('Hello from {}'.format(__file__))
submod.say_hello()
stdout:标准输出:
Hello from urls.py
Hello from /somePath/heroes/views.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.