changeset 67:4f449ed51dd3

Made cmd-line args more flexible, robust, and readable.
author Atul Varma <varmaa@toolness.com>
date Thu, 30 Apr 2009 11:29:56 -0700
parents 3d5683e4b0e2
children 84bf6a3ac4ec
files openwebchat.py
diffstat 1 files changed, 43 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/openwebchat.py	Thu Apr 30 17:30:07 2009 +0000
+++ b/openwebchat.py	Thu Apr 30 11:29:56 2009 -0700
@@ -244,11 +244,49 @@
                                                          method, conv_name,
                                                          page)
 
+class Args(object):
+    def __str__(self):
+        items = []
+        for key in self.__dict__:
+            items.append('%s=%s' % (key, self.__dict__[key]))
+        return ', '.join(items)
+
+def get_args(args = sys.argv[1:], **kwargs):
+    new_args = Args()
+    regexp = re.compile(r'([A-Za-z0-9_]+)=(.*)')
+    for key in kwargs:
+        setattr(new_args, key, kwargs[key])
+
+    for arg in args:
+        match = regexp.match(arg)
+        if match:
+            key = match.group(1)
+            if key not in kwargs:
+                raise ValueError('invalid argument: %s' % key)
+            value = match.group(2)
+            constructor = type(kwargs[key])
+            if constructor == bool:
+                constructor = make_boolish
+            setattr(new_args, key, constructor(value))
+    return new_args
+
+def make_boolish(val):
+    if type(val) is not bool:
+        if val.lower() in ['true', '1', 'yes']:
+            val = True
+        elif val.lower() in ['false', '0', 'no']:
+            val = False
+        else:
+            raise ValueError('not a boolean: %s' % val)
+    return val
+
 if __name__ == '__main__':
-    if len(sys.argv) > 1:
-        port = int(sys.argv[1])
-    else:
-        port = 8071
+    args = get_args(ip = '127.0.0.1',
+                    port = 8071,
+                    is_keep_alive = True)
 
-    server = OpenWebChatServer(('127.0.0.1', port), Conversations())
+    server = OpenWebChatServer(addr = (args.ip, args.port),
+                               conversations = Conversations(),
+                               is_keep_alive = args.is_keep_alive)
+    print "Starting server with configuration: %s" % args
     server.run()