不见春山
骑马倚斜桥,满楼红袖招。
Home
Categories
Archives
Tags
About
Home
Python的跨目录引用
Python的跨目录引用
取消
Python的跨目录引用
由
ctaoist
发布于 2023-02-16
·
最后更新:2023-02-16
1
经常遇到 Python 跨目录引用报 `No module named xxxx` 错误,略微整理一下。 ## 区分Python中的一些概念 - 一个以 `.py` 结尾的文件就是一个 python module - 任意一个文件夹,只要其中包含 python module,就可以叫做 python package.(Python2的话,该文件夹内还需要包含一个 `__init__.py` 文件) 我们既可以 `import package`,也可以 `import module`,以及 `module` 下的函数、类等等 ## Python引用自定义python文件的情况 ### utils和main位于同级目录下 ``` --main.py --utils.py ``` ```py # main.py import utils # 直接引用就可以 ``` ## utils位于main下同级目录下的子目录内 ``` --main.py --dir/ ----utils.py ``` ```py # main.py from dir import utils # 也是直接引用 ``` ## utils位于main的父目录或者不同的目录 ``` --test ----utils1.py ----dir/ ------main.py ----dir2/ ------utils2.py ``` 一般默认情况下只有 `main函数` 所在的目录会被添加到 `python sys path`,所以这种情况下我们需要手动添加目录到 `path` 中。 ```py # dir/main.py import sys sys.path.append("/absolute_path") # from os import path # if path.dirname(__file__) not in sys.path: # sys.path.append(path.dirname(__file__)) import utils1, dir2.utils2 # 添加 path 后也能直接引用 ``` ### 使用 python3 -m 命令 ```sh # cd /path/test python3 -m dir.main ``` 这种情况就不需要追加 python path。
编程语言
Python
该博客文章由作者通过
CC BY 4.0
进行授权。
分享
最近更新
Python的跨目录引用
N2N 搭建教程
RNN与LSTM
反向传播原理的理解
tensorflow-gpu 安装笔记
热门标签
虚拟组网
VPN
Tensorflow
Linux
Router
C
Mathematica
生活
pandoc
I2C
文章目录
-
反向传播原理的理解