属性错误:模块"nats"没有属性"连接"



https://nats-io.github.io/nats.py/modules.html

Traceback (most recent call last):
File "c:Userslbnats.py", line 22, in <module>
asyncio.run(main())
File "D:anacondalibasynciorunners.py", line 44, in run
return loop.run_until_complete(main)
File "D:anacondalibasynciobase_events.py", line 616, in run_until_complete
return future.result()
File "c:Userslbnats.py", line 6, in main
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
AttributeError: module 'nats' has no attribute 'connect'

属性错误:我无法弄清楚"connect"的问题所在。

import asyncio
import nats
async def main():
# Connect to NATS!
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
# Receive messages on 'foo'
sub = await nc.subscribe("foo")
# Publish a message to 'foo'
await nc.publish("foo", b'Hello from Python!')
# Process a message
msg = await sub.next_msg()
print("Received:", msg)
# Close NATS connection
await nc.close()
if __name__ == '__main__':
asyncio.run(main())

请帮我解决这个连接问题。

解决方案是将文件重命名为其他文件。

当您键入import nats时,python会递归地尝试查找名为nats的文件或文件夹。在这种情况下,如果找到的第一个文件是nats.py

您永远不会在nats.py中定义一个名为connect的函数,这样就会失败。相反,您希望递归导入继续到site_packages,其中实际的nats文件夹包含连接函数。

例如,如果将此文件命名为hello.py:

import hello
print(hello.hello)
print(hello)
print(hello.hello.hello)

您将看到所有3个print语句都打印相同的内容,因为hello将是文件本身。

简单地将文件重命名为其他任何名称都可以防止python过早地找到模块,并将继续搜索,直到找到正确的模块。

我刚刚运行了您的代码,没有出现任何错误。尝试卸载并重新安装nats:

pip install nats-py

最新更新