3 import os, sys, time, readline, atexit, re
5 from osrf.system import osrfConnect
6 from osrf.json import *
7 from osrf.ses import osrfClientSession
8 from osrf.conf import osrfConfigValue
11 # -------------------------------------------------------------------
13 # -------------------------------------------------------------------
18 #line = raw_input("srfsh% ")
19 line = raw_input("\033[01;32msrfsh\033[01;34m% \033[00m")
22 if lower(line) == 'exit' or lower(line) == 'quit':
28 if command == 'request':
33 if command == 'math_bench':
35 handle_math_bench(parts)
52 except KeyboardInterrupt:
60 # -------------------------------------------------------------------
61 # Set env variables to control behavior
62 # -------------------------------------------------------------------
63 def handle_set(parts):
64 m = re.compile('(.*)=(.*)').match(parts[0])
68 print "%s = %s" % (key, val)
70 def handle_get(parts):
72 print get_var(parts[0])
77 # -------------------------------------------------------------------
79 # -------------------------------------------------------------------
86 - runs <count> opensrf.math requests and reports the average time
88 request <service> <method> [<param1>, <param2>, ...]
89 - performs an opensrf request
92 - sets an environment variable
94 Environment variables:
95 SRFSH_OUTPUT = pretty - print pretty JSON and key/value pairs for network objects
96 = raw - print formatted JSON
102 # -------------------------------------------------------------------
103 # performs an opensrf request
104 # -------------------------------------------------------------------
105 def handle_request(parts):
106 service = parts.pop(0)
107 method = parts.pop(0)
108 jstr = '[%s]' % join(parts)
112 params = osrfJSONToObject(jstr)
114 print "Error parsing JSON: %s" % jstr
117 ses = osrfClientSession(service)
122 req = ses.request2(method, tuple(params))
126 resp = req.recv(timeout=120)
128 total = time.time() - start
131 otp = get_var('SRFSH_OUTPUT')
133 print "\n" + osrfDebugNetworkObject(resp.content())
135 print osrfFormatJSON(osrfObjectToJSON(resp.content()))
141 print "Total request time: %f" % total
145 def handle_math_bench(parts):
147 count = int(parts.pop(0))
148 ses = osrfClientSession('opensrf.math')
152 if i % 10: sys.stdout.write('.')
153 else: sys.stdout.write( str( i / 10 ) )
157 for i in range(count):
159 starttime = time.time()
160 req = ses.request('add', 1, 2)
161 resp = req.recv(timeout=2)
162 endtime = time.time()
164 if resp.content() == 3:
165 sys.stdout.write("+")
167 times.append( endtime - starttime )
169 print "What happened? %s" % str(resp.content())
172 if not ( (i+1) % 100):
173 print ' [%d]' % (i+1)
177 for i in times: total += i
178 print "\naverage time %f" % (total / len(times))
183 # -------------------------------------------------------------------
184 # Defines the tab-completion handling and sets up the readline history
185 # -------------------------------------------------------------------
186 def setup_readline():
187 class SrfshCompleter(object):
188 def __init__(self, words):
192 def complete(self, prefix, index):
193 if prefix != self.prefix:
194 # find all words that start with this prefix
195 self.matching_words = [
196 w for w in self.words if w.startswith(prefix)
200 return self.matching_words[index]
204 words = 'request', 'help', 'exit', 'quit', 'opensrf.settings', 'opensrf.math', 'set'
205 completer = SrfshCompleter(words)
206 readline.parse_and_bind("tab: complete")
207 readline.set_completer(completer.complete)
209 histfile = os.path.join(get_var('HOME'), ".srfsh_history")
211 readline.read_history_file(histfile)
214 atexit.register(readline.write_history_file, histfile)
217 file = os.path.join(get_var('HOME'), ".srfsh.xml")
218 print_green("Connecting to opensrf...")
219 osrfConnect(file, 'srfsh')
223 # Load the user defined external plugins
224 # XXX Make this a real module interface, with tab-complete words, commands, etc.
226 plugins = osrfConfigValue('plugins')
229 # XXX standard srfsh.xml does not yet define <plugins> element
230 print_red("No plugins defined in /srfsh/plugins/plugin\n")
233 plugins = osrfConfigValue('plugins.plugin')
234 if not isinstance(plugins, list):
237 for module in plugins:
238 name = module['module']
239 init = module['init']
240 print_green("Loading module %s..." % name)
243 str = 'from %s import %s\n%s()' % (name, init, init)
248 sys.stderr.write("\nError importing plugin %s, with init symbol %s: \n%s\n" % (name, init, e))
251 if not get_var('SRFSH_OUTPUT'):
252 set_var('SRFSH_OUTPUT', 'pretty')
255 def set_var(key, val):
256 os.environ[key] = val
260 try: return os.environ[key]
264 def print_green(str):
265 sys.stdout.write("\033[01;32m")
266 sys.stdout.write(str)
267 sys.stdout.write("\033[00m")
271 sys.stdout.write("\033[01;31m")
272 sys.stdout.write(str)
273 sys.stdout.write("\033[00m")