首页 > 解决方案 > python3使用模块内部的内部依赖解决相对导入

问题描述

我的文件夹结构:

grpc/
    server.py
    client.py
    ...    
    src/
        __init__.py
        image_pb2.py
        image_pb2_grpc.py 
        ...

server.py

import image_pb2_grpc
import image_pb2

...

image_pb_grpc.py

import image_pb2
...

总之,server既取决于image_pb2image_pb2_grpc,同时image_pb2_grpc也取决于image_pb2

现在,如果我将文件夹移到server.py里面src,代码肯定运行良好,因为一切都在路径中。

问题server.py应该在src文件夹之外。

现在,我仍然可以通过更改server.py和来解决问题image_pb2_grpc.py

server.py

from src import image_pb2_grpc
from src import image_pb2

...

image_pb_grpc.py

from src import image_pb2
...

这种方法的问题是,我需要image_pb_grpc.py手动更改,因为它们是从 grpc 生成的代码,并且它们是使用 bash 脚本生成的,因此无法手动更改它们。

我怎样才能组织我的项目,以便我可以在server外面跑src,而不改变image_pb2image_pb2_grpc

标签: pythonpython-3.xpython-importgrpc-pythonrelative-import

解决方案


运行脚本的正确方法是:

$ cd grpc
$ python -m server # this is the one you want to run

使用 server.py 中的相对导入。

如果这不起作用,恐怕您需要破解 sys.path - 但应该不惜一切代价避免这种情况

编辑:

在服务器中导入image_pb2as in from .src import image_pb2do

sys.modules['image_pb2'] = sys.modules['src.image_pb2']

然后导入 image_pb2_grpc。不要在其中添加任何导入__init__.py


推荐阅读