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.

Full duplex messaging between web browsers and servers

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

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

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

      data = []

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

      var ws = new WebSocket('ws://localhost:8080'  + "/");
      data = []
      ws.onopen = function() { = '#000';
      ws.onclose = function() { = null;
      ws.onmessage = function(event) {
        data = []
        document.getElementById('count').innerHTML = data[0];

</html> (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 />'))

No comments:

Post a Comment