changeset 3:f81d17014d31

Implement runv()
author Thinker K.F. Li <thinker@codemud.net>
date Mon, 28 Mar 2011 23:24:34 +0800
parents 369dd74706b3
children d502e401e136
files pysh.py
diffstat 1 files changed, 53 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/pysh.py	Mon Mar 28 22:56:55 2011 +0800
+++ b/pysh.py	Mon Mar 28 23:24:34 2011 +0800
@@ -2,26 +2,47 @@
 import os
 import comm
 
-def run(cmd):
+def _run(cmd, inplace):
     def terminate_shell(args, env, session):
         yield
         while True:
             data = session.recv()
             if data == None:
                 break
+
+            sys.stdout.write(data)
             yield
             pass
         session.exit(0)
         server.close()
         pass
-    
-    prev_frame = sys._getframe().f_back
+
+    def terminate_shell_inplace(args, env, session):
+        yield
+        while True:
+            data = session.recv()
+            if data == None:
+                break
+
+            inplace_blks.append(data)
+            yield
+            pass
+        session.exit(0)
+        server.close()
+        pass
+
+    prev_frame = sys._getframe().f_back.f_back
     prev_locals = prev_frame.f_locals
     prev_globals = prev_frame.f_globals
 
     ns = dict(prev_locals)
     ns['py'] = 'python -m shell_agent'
-    ns['terminate_shell'] = terminate_shell
+    if inplace:
+        inplace_blks = []
+        ns['terminate_shell'] = terminate_shell_inplace
+    else:
+        ns['terminate_shell'] = terminate_shell
+        pass
     
     server = comm.server(ns)
     server.listen()
@@ -29,24 +50,47 @@
     server_addr = server.get_addr()
     ns['PYSHELL_SERVER'] = server_addr
 
-    env = ';'.join(['export %s="%s"' % (k, v)
+    env = ';'.join(['export %s="%s"' % (k, str(v).replace('\\', '\\\\').replace('"', '\\"'))
                     for k, v in ns.items()
                     if isinstance(v, (str, int, float))])
-    env = env + ';py=\"python -m shell_agent\"'
     
     pid = os.fork()
     if pid == 0:
-        os.system(env + ';' + cmd + '; $py terminate_shell')
+        os.system(env + ';(' + cmd + ')| $py terminate_shell')
+        sys.exit(0)
         pass
     
     server.handle()
+
+    if inplace:
+        return ''.join(inplace_blks)
+    pass
+
+def run(cmd):
+    _run(cmd, inplace=False)
     pass
 
 def runv(cmd):
-    pass
+    txt = _run(cmd, inplace=True)
+    return txt
 
 if __name__ == '__main__':
+    def add_prefix(args, env, session):
+        yield
+        while True:
+            data = session.recv()
+            if data == None:
+                break
+            session.send(args[0] + data)
+            yield
+            pass
+        session.exit(0)
+        pass
+    
     for i in range(20):
-        run('echo $i')
+        run('echo $i|$py add_prefix "hello: "')
         pass
+
+    txt = runv('echo HELLO').strip()
+    print 'inplace value: %s' % (txt)
     pass