【问题标题】:Cannot import name 'pb'无法导入名称“pb”
【发布时间】:2016-09-07 16:03:57
【问题描述】:

我正在使用 Twisted 16.1.1 和 python 3.4。在twisted 16.1.1 版的文档中,there is a tutorial 上面写着“from twisted.spread import pb”。但是当我尝试导入它时,它给出了一个例外。我究竟做错了什么?

Traceback (most recent call last):
File "main.py", line 10, in <module>
from twisted.spread import pb
ImportError: cannot import name 'pb'

我正在关注this tutorial。这是我的代码:

from twisted.internet import reactor
from twisted.spread import pb

class Echoer(pb.Root):
    def remote_echo(self, st):
        print('echoing:', st)
        return st

if __name__ == '__main__':
    reactor.listenTCP(8789, pb.PBServerFactory(Echoer()))
    reactor.run()

/usr/lib64/python3.4/site-packages/twisted/spread 上有一个名为ui 的文件夹。没有名为 pb 的文件夹/文件。

我将pb.py 文件复制到我的python 文件夹中,现在当我尝试导入pb 时出现异常:

Traceback (most recent call last):
File "main.py", line 2, in <module>
from twisted.spread import pb
File "/usr/lib64/python3.4/site-packages/Twisted-16.1.1-py3.4.egg/twisted/spread/pb.py", line 890
except Error, e:
            ^
SyntaxError: invalid syntax

发生了什么?

【问题讨论】:

  • 您是否运行setup.py 文件将twisted 正确添加到python 中?
  • 我是从 pip 安装的...
  • 我可以导入from twisted.internet import reactor,但是pb没有。
  • 能否请您发布代码?没有任何明显的原因应该失败。另外,您是否在该目录的任何位置创建了一个名为 pb.py 的文件?
  • 如果您查看twisted python 3 移植图(rawgit.com/mythmon/twisted-py3-graph/master/index.html),您会看到twisted.spread.pb 尚未移植。它目前仅适用于 python 2。

标签: python python-3.x twisted


【解决方案1】:

SyntaxError 的原因是 except Error, e: 仅在 Python 2 中有效。在 Python 3 中,它会写成 except Error as e:

问题不在于您的代码。底层模块尚未更新到 Python 3。

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 2020-02-05
    • 2011-07-11
    • 2018-06-11
    • 2014-11-20
    • 2014-03-04
    • 2017-01-11
    • 2013-03-13
    • 2014-02-25
    相关资源
    最近更新 更多