PythonSharp (1) A minimal Web Server

Past month I presented my work on PythonSharp at Argentina PyCon 2012 (see Spanish post), a Python interpreter that I am writing in C#. As in other of my interpreter implementations, it can access native types. As a proof of concept, I wrote a minimal web server example:

from System import Array, Byte
from System.Net import HttpListener
from System.IO import Path, FileStream, FileMode, File

root = "c:/apache-tomcat-6.0.18/webapps/docs"

bytes = Array.CreateInstance(Byte,1024)

listener = HttpListener()

def process(context):
    filename = context.Request.Url.AbsolutePath
    if not filename or filename == '/':
        filename = "index.html"
    if filename[0] == '/':
        filename = filename[1:]
    filename = Path.Combine(root, filename)
    if not File.Exists(filename):
    input = FileStream(filename, FileMode.Open)
    bytes = Array.CreateInstance(Byte, 1024 * 16)
    nbytes = input.Read(bytes, 0, bytes.Length)
    while nbytes>0:
        context.Response.OutputStream.Write(bytes, 0, nbytes)
        nbytes = input.Read(bytes, 0, bytes.Length)


while True:
    context = listener.GetContext()
    print("new request")

The file at repo:

To run the example, you should compile the solution. PythonSharp.Console project compiles to pysh.exe console program. You can change the root variable value, now it points to a set of static files in my disk, with Tomcat docs 😉 :


The code is based on my previous examples:

A Minimal Http Server In C#

A Minimal Http Server in Java

I can import .NET namespaces and manage them as modules. I’m working with .NET 3.5 (I like to use the minimal requirements) so I could not use other approaches to copy a file to the output response stream, see:

Best way to copy between two Stream instances

Now, I’m working on having the same implementation for my AjTalk Smalltalk virtual machine. But that’s a topic for another post.

Keep tuned!

Angel “Java” Lopez

One thought on “PythonSharp (1) A minimal Web Server

  1. Pingback: AjTalk In C# (2): A Simple Web Server « Angel ”Java” Lopez on Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s