python - 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_pb2
和image_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_pb2
或image_pb2_grpc
?
解决方案
运行脚本的正确方法是:
$ cd grpc
$ python -m server # this is the one you want to run
使用 server.py 中的相对导入。
如果这不起作用,恐怕您需要破解 sys.path - 但应该不惜一切代价避免这种情况
编辑:
在服务器中导入image_pb2
as in from .src import image_pb2
do
sys.modules['image_pb2'] = sys.modules['src.image_pb2']
然后导入 image_pb2_grpc。不要在其中添加任何导入__init__.py
推荐阅读
- java - 我们如何访问子类覆盖的超类方法?怎么可能在内存级别?
- java - Apache Netbeans 中缺少 Java 类别
- sql - 使用 PIVOT 的 NULL 字段
- linux - GTK 程序什么都不做
- selenium - 当 selenium-server-standalone 作为 Windows 服务运行时,无法初始化 Chrome WebDriver
- c - insmod:错误:无法插入模块 dvb-usb-it913x.ko:模块中的未知符号
- c++ - 如何使用带有特殊整数的输入重定向作为分隔符,直到 eof
- java - 无法使用 Collections(Java) 对文件名包含时间戳的文件列表进行排序
- sql - 使用连续的行对计算值,包括最后一行的值
- ssl - 我可以使用 LetsEncrypt 为我不拥有的子域颁发证书吗?