forked from jverhoeven/pyzmqrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zmqsnoop.py
57 lines (43 loc) · 1.63 KB
/
zmqsnoop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'''
Created on Mar 31, 2014
@author: Jan Verhoeven
@note: This utility prints all messages published on a PUB endpoint by connecting
a SUB socket to it. All message are line split and prefixed with a '>' character.
@copyright: MIT license, see http://opensource.org/licenses/MIT
'''
from __future__ import print_function
import argparse
import sys
import signal
import zmq
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Reads and prints messages from a remote pub socket.')
parser.add_argument('--sub', nargs='+', required=True, help='The PUB endpoint')
args = parser.parse_args()
print("Starting zmqsnoop...")
# Handle OS signals (like keyboard interrupt)
def signal_handler(_, __):
print('Ctrl+C detected. Exiting...')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
try:
context = zmq.Context()
# Subscribe to all provided end-points
sub_socket = context.socket(zmq.SUB)
sub_socket.setsockopt(zmq.SUBSCRIBE, b'')
for sub in args.sub:
sub_socket.connect(sub)
print("Connected to {0}".format(sub))
while True:
# Process all parts of the message
try:
message_lines = sub_socket.recv_string().splitlines()
except Exception as e:
print("Error occured with exception {0}".format(e))
for line in message_lines:
print(">" + line)
except Exception as e:
print("Connection error {0}".format(e))
# Never gets here, but close anyway
sub_socket.close()
print("Exiting zmqsnoop...")