question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to close websocket/stream using ctrl-c ?

See original GitHub issue

Hi! Firstly thank you for this awesome project.

Sorry, if I ask, but I don’t understand how to stop a running script in while Trueloop with ctrl-c and close everything properly. I tried to use the following code , however, the stream keeps printing and doesn’t stop the process. What is the proper and clean way to do this?

from binance.websockets import BinanceSocketManager
from unicorn_fy.unicorn_fy import UnicornFy
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager

import logging
import os
import time
import threading

def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            try:
                # remove # to activate the print function:
                print(oldest_stream_data_from_stream_buffer)
            except Exception:
                # not able to process the data? write it back to the stream_buffer
                binance_websocket_api_manager.add_to_stream_buffer(oldest_stream_data_from_stream_buffer)


if __name__ == '__main__':
    try:
        binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
        # start a worker process to process to move the received stream_data from the stream_buffer to a print function
        worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
        worker_thread.start()

        kline_stream_id = binance_websocket_api_manager.create_stream(['kline', 'kline_1m'], ['btcusdt'])

    except KeyboardInterrupt:
        binance_websocket_api_manager.stop_stream(kline_stream_id)
        binance_websocket_api_manager.stop_manager_with_all_streams()

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
mfirocommented, Nov 20, 2020

This solves the problem:

if __name__ == '__main__':
    binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")

    # start a worker process to process to move the received stream_data from the stream_buffer to a print function
    worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
    worker_thread.start()
    kline_stream_id = binance_websocket_api_manager.create_stream(['kline', 'kline_1m'], ['btcusdt'])

    try:
        while True:
            time.sleep(60)
    
    except KeyboardInterrupt:
        binance_websocket_api_manager.stop_stream(kline_stream_id)
        binance_websocket_api_manager.stop_manager_with_all_streams()

The exception is also caught properly. The time.sleep() amount doesn’t matter also in functionality as far as I’ve experienced.

1reaction
oliver-zehentleitnercommented, Nov 20, 2020

Thank you very much for sharing your solution! I think i am going to put it into an example! best regards!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to close websocket/stream using ctrl-c ? #130 - GitHub
In Windows 10 it doens't stop. I tried to hit ctrl-c multiple time. Actually the problem is that KeyboardInterrupt exception is not caught...
Read more >
How to close socket connection on Ctrl-C in a python ...
This can be resolved by using the socket.SO_REUSEADDR flag. For eg: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.
Read more >
Possible to cleanly shutdown asyncio & websockets?
I am running websockets in asyncio and here is what I do. Scenario 1: User hits control-c. Code: Select all except KeyboardInterrupt: for...
Read more >
Part 1 - Send & receive - websockets 10.4 documentation
Switch to the shell where the server is running and check that the server received the message. Good! Exit the interactive client with...
Read more >
WebSockets - UWP applications - Microsoft Learn
WebSockets provide a mechanism for fast, secure, two-way communication between a client and a server over the web using HTTP(S), ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found