Python GRPC无法导入生成的文件
我正在尝试使用 GRPC 教程 使用 GRPC 我生成了两个文件
helloworld_pb2_grpc.py
helloworld_pb2.py
:尝试将这些文件放在一个名为 PB 的文件夹下,文件夹结构如下:
#root/pb
helloworld_pb2_grpc.py
helloworld_pb2.py
#root/GRPC
greeter_server.py
#root/Client
greeter_client.py
当我使用相同的根文件夹运行代码时,它工作正常。但是当我将这些文件放在文件夹下时,我无法导入生成的文件。我正在使用这段代码: #GRPC/greeter_server.py import sys
# adding Folder_2 to the system path
sys.path.insert(0, '/root/pb')
from helloworld_pb2_grpc import helloworld_pb2_grpc
from helloworld_pb2 import helloworld_pb2
当我运行代码时,我得到:
Traceback (most recent call last):
File "GRPC/greeter_server.py", line 25, in <module>
from helloworld_pb2_grpc import helloworld_pb2_grpc
ImportError: cannot import name 'helloworld_pb2_grpc' from 'helloworld_pb2_grpc' (/root/pb/helloworld_pb2_grpc.py)
您可以找到文件的内容 helloworld_pb2_grpc.py , helloworld_pb2.py
I am trying to use GRPC using GRPC tutorial I have generated two files:
helloworld_pb2_grpc.py
helloworld_pb2.py
I am trying to put these files under one folder called PB and the folder structure is like:
#root/pb
helloworld_pb2_grpc.py
helloworld_pb2.py
#root/GRPC
greeter_server.py
#root/Client
greeter_client.py
When I run the code using same root folder it works fine. But when I am putting these files under the folder then I can't import the generated files. I am using this code:
#GRPC/greeter_server.py
import sys
# adding Folder_2 to the system path
sys.path.insert(0, '/root/pb')
from helloworld_pb2_grpc import helloworld_pb2_grpc
from helloworld_pb2 import helloworld_pb2
And when I run the code I am getting:
Traceback (most recent call last):
File "GRPC/greeter_server.py", line 25, in <module>
from helloworld_pb2_grpc import helloworld_pb2_grpc
ImportError: cannot import name 'helloworld_pb2_grpc' from 'helloworld_pb2_grpc' (/root/pb/helloworld_pb2_grpc.py)
You can find the content of the files helloworld_pb2_grpc.py , helloworld_pb2.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每当您尝试从另一个文件夹中导入任何 python 文件时,您可以通过在该文件夹中添加一个仅名为 __init__.py 的空 python 文件来将它们声明为模块。
这样,您的目录结构应该如下所示:
Whenever you are trying to import any python file from inside another folder, you can declare them as modules by adding an empty python file in that folder named only as
__init__.py
.With this, your directory structure should look like :