文件結構:python
.
├── utils
│ ├── util.py
│ └── class_util.py
├── src
│ └── sub_main.py
└── main.py
# utils/utils.py def get_sum(a, b): return a + b
# utils/class_utils.py class Encoder(object): def encode(self, s): return s[::-1] class Decoder(object): def decode(self, s): return ''.join(reverse(list(s)))
# main.py from utils.utils import get_sum print(get_sum(1, 2)) ########## 輸出 ########## 3
# src/sub_main.py import sys sys.path.append("..") from utils.class_utils import * encoder = Encoder() decoder = Decoder() print(encoder.encode('abcde')) print(encoder.encode('edcba')) ########## 輸出 ########## edcba abcde
如下Python代碼用命令行運行main.py會出錯,找不到proto.ubuntu
├── proto
│ ├── mat.py
├── utils
│ └── mat_mul.py
└── src
└── main.py
# proto/mat.py class Matrix(object): def __init__(self, data): self.data = data self.n = len(data) self.m = len(data[0])
# utils/mat_mul.py from proto.mat import Matrix def mat_mul(matrix_1: Matrix, matrix_2: Matrix): assert matrix_1.m == matrix_2.n n, m, s = matrix_1.n, matrix_1.m, matrix_2.m result = [[0 for _ in range(n)] for _ in range(s)] for i in range(n): for j in range(s): for k in range(m): result[i][k] += matrix_1.data[i][j] * matrix_2.data[j][k] return Matrix(result)
# src/main.py from proto.mat import Matrix from utils.mat_mul import mat_mul a = Matrix([[1, 2], [3, 4]]) b = Matrix([[5, 6], [7, 8]]) print(mat_mul(a, b).data) ########## 輸出 ########## [[19, 22], [43, 50]]
有兩個方法解決:windows
1.在文件中強行修改sys.path[0]:app
import sys sys.path[0] = '/home/ubuntu/workspace/your_projects'
2.在Python的虛擬環境中的activate文件,增長:(windows系統中無效)模塊化
export PYTHONPATH="/home/ubuntu/workspace/your_projects"
極客時間《Python核心技術與實戰》專欄spa