Friday, September 2, 2016

CURIO and Websocketd

Quote from site :

Curio is a library for performing concurrent I/O and common system programming tasks such as launching subprocesses and farming work out to thread and process pools. It uses Python coroutines and the explicit async/await syntax introduced in Python 3.5. Its programming model is based on cooperative multitasking and existing programming abstractions such as threads, sockets, files, subprocesses, locks, and queues. You'll find it to be small and fast. https://github.com/dabeaz/curio

websocketd
Full duplex messaging between web browsers and servers

run the bellow python script 'ls.py' with the following command :
./websocketd --port=8080 python ls.py


In an html page put the folowing code
and in the web browser console enter for example: ws.send('ls /home')

<!DOCTYPE html>
<html>
  <head>
    <title>websocketd unix command example</title>
    <style>
      #count {
        font:  16px arial;
        margin: auto;
        color: #00FF00;
      }
    </style>
  </head>
  <body>
    <div style="color: #fff;">Python Terminal</div>
    <div id="count" style="height:500px; overflow:auto; border:1px solid black;"></div>

    <script>
      data = []

      function clearDiv() {
        var div = document.getElementById('count');
        div.innerHTML = "";
      }

      var ws = new WebSocket('ws://localhost:8080'  + "/");
      data = []
      ws.onopen = function() {
        document.body.style.backgroundColor = '#000';
      };
      ws.onclose = function() {
        document.body.style.backgroundColor = null;
      };
      ws.onmessage = function(event) {
        data = []
        data.push(event.data)
        document.getElementById('count').innerHTML = data[0];
        console.log(data.length)
      };
    </script>

  </body>
</html>


ls.py (modified version from the examples site)
import curio
from sys import stdout
from curio import subprocess


async def main():
    while True:
        data = b""
        path = input()
        p = subprocess.Popen(["ls", "-rtl", path], stdout=subprocess.PIPE, bufsize=1)
        async for line in p.stdout:
            data += line
        print(data.decode('UTF-8').replace('\n','<br />'))
        stdout.flush()

curio.run(main())