问题:我正在尝试安装 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/