简体   繁体   English

Python 和导入

[英]Python and the imports

I have a python project where I use grpc.我有一个使用 grpc 的 python 项目。 I create the files with python -m grpc_tools.protoc -I "pathToMyProtoFile" --python_out=. --grpc_python_out=. "pathToMyProtoFile\\module.proto"我使用python -m grpc_tools.protoc -I "pathToMyProtoFile" --python_out=. --grpc_python_out=. "pathToMyProtoFile\\module.proto"创建文件python -m grpc_tools.protoc -I "pathToMyProtoFile" --python_out=. --grpc_python_out=. "pathToMyProtoFile\\module.proto" python -m grpc_tools.protoc -I "pathToMyProtoFile" --python_out=. --grpc_python_out=. "pathToMyProtoFile\\module.proto"

I want all the grpc-stuff to be in a python package.我希望所有的 grpc 东西都在一个 python 包中。 So I created a sub folder "my_package_folder" and added an empty __init__.py in it.所以我创建了一个子文件夹“my_package_folder”并在其中添加了一个空的__init__.py

My Problem: How to access and where to place the generated module_pb2.py and module_pb2_grpc.py .我的问题:如何访问以及放置生成的module_pb2.pymodule_pb2_grpc.py

If I place them into the root folder of my application I cannot access them from my package with from .. import module_pb2_grpc "attempted relative import beyond top-level package"如果我将它们放在我的应用程序的根文件夹中,我将无法从我的包中访问它们from .. import module_pb2_grpc “尝试在顶级包之外进行相对导入”

If I place them into my "my_package_folder" the 2 generated files do not find each other.如果我将它们放入“my_package_folder”,则生成的 2 个文件不会相互找到。 ( import module_pb2 as module__pb2 in "module_pb2_grpc.py") (在“module_pb2_grpc.py” import module_pb2 as module__pb2 module_pb2 import module_pb2 as module__pb2

This import mechanism in python is so extremely confusing... I have no idea where to start to solve this problem. python中的这种导入机制非常令人困惑......我不知道从哪里开始解决这个问题。

My folder structure is just the main project folder and a sub folder "my_package_folder" for all the grpc stuff.我的文件夹结构只是主项目文件夹和所有 grpc 内容的子文件夹“my_package_folder”。

Let's say you have a folder structure like this.假设您有这样的文件夹结构。 I'm just taking the example of one file.我只是以一个文件为例。

├── module_pb2_grpc.py
├── my_package_folder
│   ├── __init__.py

Then to resolve the attempted relative import beyond top-level package , you can add this.然后要解决在attempted relative import beyond top-level package ,您可以添加它。

init .py初始化.py

import os
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from module_pb2_grpc import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM