简体   繁体   English

websocket-client 不适用于 Python3/VSCode

[英]websocket-client will not work on Python3/VSCode

I am trying to use websocket-client package in Python 3.10 with VSCode on Windows 10. I am able to get the exact same code running on an Ubuntu 20.04 VM with Python 3.10.1我正在尝试在 Windows 10 上使用带有 VSCode 的 Python 3.10 中的 websocket-client 包。我能够在带有 Python 3.10.1 的 Ubuntu 20.04 VM 上运行完全相同的代码

Here is my websocket-client version:这是我的 websocket 客户端版本:

Name: websocket-client
Version: 1.2.3
Summary: WebSocket client for Python with low level API options
Home-page: https://github.com/websocket-client/websocket-client.git
Author: liris
Author-email: liris.pp@gmail.com
License: Apache-2.0
Location: c:\users\dazk2\appdata\local\programs\python\python310\lib\site-packages
Requires:
Required-by:

I get the error:我得到错误:

Traceback (most recent call last):
  File "c:\...\websocket.py", line 32, in <module>
    ws = websocket.WebSocketApp("ws://localhost:8765",
AttributeError: module 'websocket' has no attribute 'WebSocketApp'. Did you mean: 'websocket'?

This is the code: (This isn't what I'm working on, but sample code I tried, and it still didn't work)这是代码:(这不是我正在处理的,但我尝试了示例代码,但它仍然没有工作)

import websocket
import _thread as thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, a, b):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
#    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8765",
                                 on_message = on_message,
                                 on_error = on_error,
                                 on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()    

Your file name is websocket.py , and this is overwriting the websocket library import that is importing websocket .您的文件名为websocket.py ,这将覆盖正在导入websocket的 websocket 库导入。 In essence, what you are doing, is importing the file to itself, and since the file itself doesn't have a WebSocketApp call, it crashes.本质上,您正在做的是将文件导入自身,并且由于文件本身没有WebSocketApp调用,因此它崩溃了。 Python correctly detects that it exists in the websocket library though (based on the crash suggestion), but since both use the same name, this causes a conflict.尽管 Python 正确检测到它存在于websocket库中(基于崩溃建议),但由于两者使用相同的名称,这会导致冲突。

If you rename your file to something different the library import should work as expected, and your coded should run.如果您将文件重命名为不同的名称,则库导入应按预期工作,并且您的编码应该运行。

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

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