29

I'm trying to connect to an API with python, using WebSocketApp, and I cannot seem to do it. No matter what I try, I keep getting this error:

AttributeError: 'module' object has no attribute 'WebSocketApp'

Here is the simple code I am using

import websocket
import json

def on_open(ws):
    json_data = json.dumps({'data':'value'})
    ws.send(json_data)

def on_message(ws, message):
    print('data update: %s' % message)

if __name__ == "__main__":
    apiUrl = "appurl"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()

Any help will be greatly appreciated, all the solutions I have found online have not worked for me.

5 Answers 5

39

It looks like you're trying to use features of the websocket-client package and not just the websocket package. Pip-install websocket-client from the command line (or install it using whatever other package manager you have), then try running your code again.

pip install websocket-client
Sign up to request clarification or add additional context in comments.

Comments

38

In this case, You should uninstall the possible inconsistent previous versions and install websocket-client again:

pip uninstall websocket-client
pip uninstall websocket

an then install a new version:

pip install websocket-client

Comments

26

Make sure that you didn't name your file as websocket.py; Otherwise, it will prevent import of the desired third-party module websocket; because your module is searched first according to sys.path module search path.

Rename your module to other name, and make sure to clean websocket.pyc if there it is.

2 Comments

In my case I named the file as socket.py changing it to something else did the trick
I came to this answer twice, for two different reasons. The first time the solution was this one, the second time it was this one.
0

The issue can be generated because the version. Version v1.3 and above does me the same problem but installing v1.2.3 the issue disappeared...

Comments

-1

The problem is that you possibly installed both websocket and websocket-client. Remove websocket and just let websocket-client

1 Comment

This answer does not add much to the answers stackoverflow.com/a/42144096 and stackoverflow.com/a/53444938

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.