2 import os, sys, time, readline, atexit, re
4 from osrf.system import osrfConnect
5 from osrf.json import *
6 from osrf.ses import osrfClientSession
7 from osrf.conf import osrfConfigValue
10 # -------------------------------------------------------------------
12 # -------------------------------------------------------------------
17 #line = raw_input("srfsh% ")
18 line = raw_input("\033[01;32msrfsh\033[01;34m% \033[00m")
21 if lower(line) == 'exit' or lower(line) == 'quit':
27 if command == 'request':
32 if command == 'math_bench':
34 handle_math_bench(parts)
51 except KeyboardInterrupt:
59 # -------------------------------------------------------------------
60 # Set env variables to control behavior
61 # -------------------------------------------------------------------
62 def handle_set(parts):
63 m = re.compile('(.*)=(.*)').match(parts[0])
67 print "%s = %s" % (key, val)
69 def handle_get(parts):
71 print get_var(parts[0])
76 # -------------------------------------------------------------------
78 # -------------------------------------------------------------------
85 - runs <count> opensrf.math requests and reports the average time
87 request <service> <method> [<param1>, <param2>, ...]
88 - performs an opensrf request
91 - sets an environment variable
93 Environment variables:
94 SRFSH_OUTPUT = pretty - print pretty JSON and key/value pairs for network objects
95 = raw - print formatted JSON
101 # -------------------------------------------------------------------
102 # performs an opesnrf request
103 # -------------------------------------------------------------------
104 def handle_request(parts):
105 service = parts.pop(0)
106 method = parts.pop(0)
107 jstr = '[%s]' % join(parts)
111 params = osrfJSONToObject(jstr)
113 print "Error parsing JSON: %s" % jstr
116 ses = osrfClientSession(service)
121 req = ses.request2(method, tuple(params))
125 resp = req.recv(timeout=120)
127 total = time.time() - start
130 otp = get_var('SRFSH_OUTPUT')
132 print "\n" + osrfDebugNetworkObject(resp.content())
134 print osrfFormatJSON(osrfObjectToJSON(resp.content()))
140 print "Total request time: %f" % total
144 def handle_math_bench(parts):
146 count = int(parts.pop(0))
147 ses = osrfClientSession('opensrf.math')
151 if i % 10: sys.stdout.write('.')
152 else: sys.stdout.write( str( i / 10 ) )
156 for i in range(count):
158 starttime = time.time()
159 req = ses.request('add', 1, 2)
160 resp = req.recv(timeout=2)
161 endtime = time.time()
163 if resp.content() == 3:
164 sys.stdout.write("+")
166 times.append( endtime - starttime )
168 print "What happened? %s" % str(resp.content())
171 if not ( (i+1) % 100):
172 print ' [%d]' % (i+1)
176 for i in times: total += i
177 print "\naverage time %f" % (total / len(times))
182 # -------------------------------------------------------------------
183 # Defines the tab-completion handling and sets up the readline history
184 # -------------------------------------------------------------------
185 def setup_readline():
186 class SrfshCompleter(object):
187 def __init__(self, words):
191 def complete(self, prefix, index):
192 if prefix != self.prefix:
193 # find all words that start with this prefix
194 self.matching_words = [
195 w for w in self.words if w.startswith(prefix)
199 return self.matching_words[index]
203 words = 'request', 'help', 'exit', 'quit', 'opensrf.settings', 'opensrf.math', 'set'
204 completer = SrfshCompleter(words)
205 readline.parse_and_bind("tab: complete")
206 readline.set_completer(completer.complete)
208 histfile = os.path.join(get_var('HOME'), ".srfsh_history")
210 readline.read_history_file(histfile)
213 atexit.register(readline.write_history_file, histfile)
216 file = os.path.join(get_var('HOME'), ".srfsh.xml")
217 print_green("Connecting to opensrf...")
218 osrfConnect(file, 'srfsh')
222 # Load the user defined external plugins
223 # XXX Make this a real module interface, with tab-complete words, commands, etc.
224 plugins = osrfConfigValue('plugins')
225 plugins = osrfConfigValue('plugins.plugin')
226 if not isinstance(plugins, list):
229 for module in plugins:
230 name = module['module']
231 init = module['init']
232 print_green("Loading module %s..." % name)
235 str = 'from %s import %s\n%s()' % (name, init, init)
240 sys.stderr.write("\nError importing plugin %s, with init symbol %s: \n%s\n" % (name, init, e))
243 if not get_var('SRFSH_OUTPUT'):
244 set_var('SRFSH_OUTPUT', 'pretty')
247 def set_var(key, val):
248 os.environ[key] = val
252 try: return os.environ[key]
256 def print_green(str):
257 sys.stdout.write("\033[01;32m")
258 sys.stdout.write(str)
259 sys.stdout.write("\033[00m")
263 sys.stdout.write("\033[01;31m")
264 sys.stdout.write(str)
265 sys.stdout.write("\033[00m")