Skip to content

Commit d1ccd79

Browse files
Add --json output switch for ocs-client-cli listen mode (#438)
* Add --json output switch for ocs-client-cli listen mode The output can then be filtered using jq or similar tools. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f2f6df1 commit d1ccd79

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

ocs/client_cli.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import sys
33
import code
4+
import json
45
import readline
56
import rlcompleter
67
import re
@@ -67,6 +68,7 @@ def get_parser():
6768

6869
# scan
6970
p = client_sp.add_parser('listen', help="Subscribe to feed(s) and dump to stdout.")
71+
p.add_argument('--json', action='store_true', help="Format output as json, for consumption by jq.")
7072
p.add_argument('feed_selector', help="Feed name, which can include wildcard matching (double "
7173
" ..). E.g., try 'observatory..feeds.heartbeat'")
7274

@@ -96,7 +98,12 @@ def listen(parser, args):
9698
if not use_twisted:
9799
parser.error('The "listen" function requires twisted and autobahn packages.')
98100
feeds = args.feed_selector
99-
print(f'Subscribing to {feeds}')
101+
102+
if args.json:
103+
# Write directly stdout to avoid decoration by logger.
104+
fout = sys.stdout
105+
else:
106+
print(f'Subscribing to {feeds}')
100107

101108
class Listener(ApplicationSession):
102109
@defer.inlineCallbacks
@@ -106,7 +113,12 @@ def onJoin(self, details):
106113
yield self.subscribe(self.on_event, topic, options=options)
107114

108115
def on_event(self, msg, details=None):
109-
print(f'[{details.topic}] {msg}')
116+
if args.json:
117+
j = {'topic': details.topic,
118+
'message': msg}
119+
fout.write(json.dumps(j) + '\n')
120+
else:
121+
print(f'[{details.topic}] {msg}')
110122

111123
def onDisconnect(self):
112124
if reactor.running:

0 commit comments

Comments
 (0)