Python相对导入语法: `from . import abc.xyz`

标签 python protocol-buffers

问题:我正在尝试安装 a Python3 port of Google Protocol Buffers 。当我进行 python3 setup.py 测试 时,出现以下错误:

    File "/[*snip*]/python3-protobuf-master/python/google/protobuf/unittest_custom_options_pb2.py", line 13
    from . import google.protobuf.descriptor_pb2
                        ^
SyntaxError: invalid syntax

然后我在 Python3 和 Python2 解释器中尝试了类似的语法,并得到了相同的错误:

Python 3.2.3 (default, Jul 23 2012, 16:48:24)
[GCC 4.5.3] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from . import x.y
  File "<stdin>", line 1
    from . import x.y
                   ^
SyntaxError: invalid syntax

问题:什么时候从 . import abc.xyz 有效的 Python 语法(如果有的话)?我有兴趣知道我下载的这段代码是否本质上是错误的。

杂项:我从this SO question.上的答案中选择了GPB的Python3端口。就 GPB 而言,它不是最新的,但我希望它仍然可以运行。如果您更了解 GPB 的 Python3 端口,请告诉我。

最佳答案

您只能在 import 之后命名顶级对象或嵌套模块。将 x 名称移至 from 子句:

from .x import y

或者对于您原来的问题:

from .google.protobuf import descriptor_pb2

看起来 .proto file in question未正确编译为 Python。快速扫描显示this to be the case :

void Generator::PrintImports() const {
  for (int i = 0; i < file_->dependency_count(); ++i) {
    string module_name = ModuleName(file_->dependency(i)->name());
    printer_->Print("try:\n");
    printer_->Print("  from . import $module$\n", "module", module_name);
    printer_->Print("except ImportError:\n");
    printer_->Print("  import $module$\n", "module", module_name);
  }
  printer_->Print("\n");
}

您需要向项目提交错误报告。

关于Python相对导入语法: `from . import abc.xyz` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21289621/

相关文章:

javascript - 无法在 Python 中从 javascript 解析 json post

python - 变分自动编码器 (VAE) 显示不一致的输出

python - 我应该如何在不丑陋的情况下在 Windows 上启动一个 Portable Python Tkinter 应用程序?

c# - Protobuf-net(反)小数序列化在使用自定义小数原型(prototype)合约(C#/C++ 互操作)时抛出

go - 将 protobuf 枚举消息发送到 grpc 服务器

python - 仅 Google 自定义搜索 Python 购物结果?

python - 添加新小部件时,滚动区域无法扩展(滚动)

c++ - Protobuf 中的 ParseFromArray 和 ParseFromString 有什么区别?

java - 使用 JNI 将 GPB 序列化数据从 Java 高效传递到 C++

c# - protobuf-net 如何实现可观的性能?