SlideShare a Scribd company logo
Python in the Browser                                                                             01/06/2010 13:45




                                            Python in the Browser
                     Web Programming with Silverlight & IronPython
 Michael Foord
 michael@voidspace.org.uk
 www.voidspace.org.uk
 @voidspace


         Python in the browser with Silverlight & IronPython

                  Introduction
                  Silverlight
                  Say Hello to Vera
                  Getting Started: One JS File
                  External Python Files
                  How it works
                  Loading the Javascript
                  Loading the Python Runtime
                  The IronPython Payload
                  Running the Python Code
                  So we can write code...
                  Using .NET APIs
                  Silverlight Toolkit
                  Try Python
                  Questions




 Introduction




           You, the Python developer, use Python because you want to, but in the browser you use
           JavaScript because you think you have to. With Silverlight you can write Python code in the

file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                  Page 1 of 12
Python in the Browser                                                     01/06/2010 13:45



           browser.


 Silverlight
           Microsoft browser plugin
           Now installed in over 50% of browsers (riastats)
           Cross platform: Windows and Mac, plus Linux with Moonlight
           Cross browser: Safari, Firefox, IE and Chrome
           Runs IronPython and IronRuby
           Sockets, threading, local browser storage APIs
           Webcam access, out of browser apps
           IronPython docs at ironpython.net/browser/

 IronPython 2.6 - the equivalent of Python 2.6.

 Silverlight features include:

           A ui system based on WPF
           Full access to the browser DOM
           Calling between Javascript and Silverlight code
           Out of browser applications
           Video, streaming media and 'deep zoom'
           Local browser storage
           Socket and threading APIs (etc)
           Lots more...


 Say Hello to Vera




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html        Page 2 of 12
Python in the Browser                                                                           01/06/2010 13:45




 Over 19000 lines of Python code (plus hundreds of lines of xaml) written over a 7 month period by two
 developers.


 Getting Started: One JS File
 Loading IronPython:

         <script
          src="http://gestalt.ironpython.net/dlr-latest.js"
          type="text/javascript"></script>

 Python in script tags:

         <script type="text/python">
             def onclick(s, e):
                 window.Alert("Hello from Python!")
             document.button.events.onclick += handler
             document.message.innerHTML = 'Hello Python!'
         </script>

 To develop a Python application in the browser, you just need your favorite text editor; so open it up,
 create a HTML file, reference dlr.js, and then you can use script-tags for running Python code.



file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                              Page 3 of 12
Python in the Browser                                                                          01/06/2010 13:45




 External Python Files
         <script type="text/python" src="repl.py"></script>

 This creates a console when you add ?console to the url.




 We can reference Python files as well as inline Python.

 The console is hooked up to sys.stdout, so your existing text-based Python scripts can come alive in the
 browser (sans reading from stdin). Also, any print statements you use in the app will show up in the
 console as well, making it a great println-debugging tool.

 Let's play around with the page a bit, adding a DOM element and changing it's HTML content to
 "Ouch!" when clicked:

 >>> dir(document)
 [..., 'CreateElement', ...]
 >>> div = document.CreateElement("div")
 >>> div.innerHTML = "Hello from Python!"
 >>> document.Body.AppendChild(div)
 >>> div.id = "message"
 >>> div.SetStyleAttribute("font-size", "24px")
 >>> def say_ouch(o, e):
 ... o.innerHTML = "Ouch!"
 ...
 >>> document.message.events.onclick += say_ouch


 How it works



file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 4 of 12
Python in the Browser                                                                            01/06/2010 13:45




 dlr.js contains a collection of functions for creating a Silverlight control on the HTML page that is
 capable of running IronPython code.


 Loading the Javascript




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                  Page 5 of 12
Python in the Browser                                                                            01/06/2010 13:45




 By default, just running dlr.js injects a Silverlight <object> tag into the page (immediately after the
 script-tag) so it can run only DOM-based scripts, and also scans for other script-tags indicating that you
 want a Silverlight rendering surface, but more on that later.


 Loading the Python Runtime




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                               Page 6 of 12
Python in the Browser                                                                         01/06/2010 13:45




 The injected Silverlight control points to a Silverlight application made specifically to embed the
 dynamic language runtime, the compiler/runtime/embedding infrastructure IronPython is built on, find all
 the Python code the HTML page uses, and executes it.

 The XAP is tiny, as the DLR and IronPython are in separate packages which are downloaded on-
 demand; the DLR and IronPython are not installed with Silverlight, so they must be downloaded with
 the application.


 The IronPython Payload




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                            Page 7 of 12
Python in the Browser                                                                          01/06/2010 13:45




 However, if the application depends on the ironpython.net binaries, the user's browser will cache them
 and they won't be re-downloaded for any other app; almost as good as being part of the installer, while
 still being able to be open-source.


 Running the Python Code




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 8 of 12
Python in the Browser                                                                          01/06/2010 13:45




 Now user-code is able to run. Each inline Python script-tag is executed as if it was one Python module,
 and all other Python files execute as their own modules.

 To allow Python to be indented inside a script tag, the margin of the first line which does not only
 contain whitespace is removed. Line numbers in the HTML are preserved, so error messages show up
 correctly.


 So we can write code...
 What about testing it? Well, Python comes batteries included.

         <script type="application/x-zip-compressed"
             src="PythonStdLib.zip"></script>

         <script type="text/python">
             if document.QueryString.ContainsKey("test"):
                 import sys
                 sys.path.append("PythonStdLib")

                           import repl
                           repl.show()


file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 9 of 12
Python in the Browser                                                                               01/06/2010 13:45



                           import unittest
                           ...

 That PythonStdLib.zip file contains the pieces of the Python standard-library that unittest depends on.

 The Python standard library is a little less than 5MB compressed, so it's not unthinkable to include the
 whole thing for development, but for deployment you should just include the dependencies; unittest's
 dependencies are 58 KB.

 When a zip file's filename is added to the path, it is treated like any other directory; import looks inside it
 to find modules. You'll also notice that import repl just worked, even though repl.py isn't in the zip file; it
 was referenced by a script-tag earlier. It works because script-tags actually represent file-system entries;
 doing open("repl.py"), or open("PythonStdLib/unittest.py") would also work.


 Using .NET APIs
 Using WritableBitmap to render fractals.




 Silverlight has a ton of functionality, and as I was only able to discuss a few Python libraries in
 Silverlight, I'll only be able to show a few Silverlight libraries being used from Python, but the entirety
 of Silverlight can be used from Python. See all the features Silverlight provides, as well as how to use
 .NET APIs in-general from Python.

 One interesting API is the WritableBitmap, which gives you per-pixel access to render whatever you
 want. For example, here its used to render a fractal. The number crunching is actually done from C#, but
 called from IronPython.

 As with any computationally-intensive operations, it's a good idea to write them in a static pre-compiled

file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                                 Page 10 of 12
Python in the Browser                                                                           01/06/2010 13:45



 language; for example the scientific-computation libraries for Python are actually written in C, but the
 library provide an API accessible to Python programmers. Unfortunately, CPython puts that
 responsibility on the library developer; not every C library can be directly consumed by Python code.
 However, this example shows that IronPython can call into any C# library, or any library written in a
 .NET language for that matter. This makes it trivial to just begin writing your application in Python, and
 then decide to convert the performance-sensitive sections to C#.

 We could also use the WritableBitmap to hook up to a webcam...


 Silverlight Toolkit
 silverlight.codeplex.com




 A rich set of user interface controls including charting components.


 Try Python




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html                             Page 11 of 12
Python in the Browser                                                     01/06/2010 13:45




 Questions
           blog.jimmy.schementi.com
           ironpythoninaction.com
           voidspace.org.uk/blog
           trypython.org




file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html       Page 12 of 12

More Related Content

PDF
Cython compiler
PDF
Introduction to TensorFlow and OpenCV libraries
ODP
Managing Plone Projects with Perl and Subversion
PPTX
API Documentation Workshop tcworld India 2015
PDF
109842496 jni
PPTX
API workshop: Deep dive into Java
ODP
Scripting in OpenOffice.org
PDF
Workshop: Introduction to Web Components & Polymer
Cython compiler
Introduction to TensorFlow and OpenCV libraries
Managing Plone Projects with Perl and Subversion
API Documentation Workshop tcworld India 2015
109842496 jni
API workshop: Deep dive into Java
Scripting in OpenOffice.org
Workshop: Introduction to Web Components & Polymer

What's hot (19)

PPT
Adobe Flex4
PDF
Defending Against Application DoS attacks
PDF
Enforce reproducibility: dependency management and build automation
PDF
The windows socket
PPTX
Web development with Python
PPT
Intro Java Rev010
PDF
Java Programming
PPT
Secure Ftp Java Style Rev004
PPTX
PPTX
C#Web Sec Oct27 2010 Final
PPTX
2018 20 best id es for python programming
RTF
Hack language
PPTX
Easy contributable internationalization process with Sphinx @ pyconsg2015
PPTX
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
PPTX
Publishing API documentation -- Workshop
PPTX
Introduction to Python.Net
PDF
FISE Integration with Python and Plone
PPTX
Composer for Magento 1.x and Magento 2
PPTX
API Documentation -- Presentation to East Bay STC Chapter
Adobe Flex4
Defending Against Application DoS attacks
Enforce reproducibility: dependency management and build automation
The windows socket
Web development with Python
Intro Java Rev010
Java Programming
Secure Ftp Java Style Rev004
C#Web Sec Oct27 2010 Final
2018 20 best id es for python programming
Hack language
Easy contributable internationalization process with Sphinx @ pyconsg2015
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Publishing API documentation -- Workshop
Introduction to Python.Net
FISE Integration with Python and Plone
Composer for Magento 1.x and Magento 2
API Documentation -- Presentation to East Bay STC Chapter
Ad

Similar to Python in the browser (20)

PPT
Cmpe202 01 Research
PDF
Python For All | Software Professionals, QA & DevOps professionals
PDF
Python for All
PPTX
python bridge course for second year.pptx
PPTX
Python 101 For The Net Developer
PDF
Anton Kasyanov, Introduction to Python, Lecture1
PDF
Python quick guide1
PDF
What is Python? (Silicon Valley CodeCamp 2014)
PDF
Python intro for Plone users
PDF
Plone is great... Python is too!
PDF
Python (part 0)
PPTX
First of all, what is Python? According t
PPTX
What is python
PPTX
Basic concepts for python web development
ODP
Behold the Power of Python
PPTX
Introduction to python
PPT
Python in telecommunications (in 7 minutes)
PPTX
Python 101 for the .NET Developer
PDF
Django Article V0
PDF
Welcome to Python Programming Language.pdf
Cmpe202 01 Research
Python For All | Software Professionals, QA & DevOps professionals
Python for All
python bridge course for second year.pptx
Python 101 For The Net Developer
Anton Kasyanov, Introduction to Python, Lecture1
Python quick guide1
What is Python? (Silicon Valley CodeCamp 2014)
Python intro for Plone users
Plone is great... Python is too!
Python (part 0)
First of all, what is Python? According t
What is python
Basic concepts for python web development
Behold the Power of Python
Introduction to python
Python in telecommunications (in 7 minutes)
Python 101 for the .NET Developer
Django Article V0
Welcome to Python Programming Language.pdf
Ad

More from PyCon Italia (20)

PDF
Feed back report 2010
PDF
Spyppolare o non spyppolare
PDF
zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"
PDF
Undici anni di lavoro con Python
PDF
socket e SocketServer: il framework per i server Internet in Python
PDF
Qt mobile PySide bindings
PDF
Python: ottimizzazione numerica algoritmi genetici
PDF
Python idiomatico
PDF
PyPy 1.2: snakes never crawled so fast
PDF
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
PDF
OpenERP e l'arte della gestione aziendale con Python
PDF
New and improved: Coming changes to the unittest module
PDF
Monitoraggio del Traffico di Rete Usando Python ed ntop
PDF
Jython for embedded software validation
PDF
Foxgame introduzione all'apprendimento automatico
PDF
Effective EC2
PDF
Django è pronto per l'Enterprise
PDF
Crogioli, alambicchi e beute: dove mettere i vostri dati.
PDF
Comet web applications with Python, Django & Orbited
ZIP
Cleanup and new optimizations in WPython 1.1
Feed back report 2010
Spyppolare o non spyppolare
zc.buildout: "Un modo estremamente civile per sviluppare un'applicazione"
Undici anni di lavoro con Python
socket e SocketServer: il framework per i server Internet in Python
Qt mobile PySide bindings
Python: ottimizzazione numerica algoritmi genetici
Python idiomatico
PyPy 1.2: snakes never crawled so fast
PyCuda: Come sfruttare la potenza delle schede video nelle applicazioni python
OpenERP e l'arte della gestione aziendale con Python
New and improved: Coming changes to the unittest module
Monitoraggio del Traffico di Rete Usando Python ed ntop
Jython for embedded software validation
Foxgame introduzione all'apprendimento automatico
Effective EC2
Django è pronto per l'Enterprise
Crogioli, alambicchi e beute: dove mettere i vostri dati.
Comet web applications with Python, Django & Orbited
Cleanup and new optimizations in WPython 1.1

Recently uploaded (20)

PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Transforming Manufacturing operations through Intelligent Integrations
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
NewMind AI Monthly Chronicles - July 2025
Sensors and Actuators in IoT Systems using pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Transforming Manufacturing operations through Intelligent Integrations
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Modernizing your data center with Dell and AMD
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Machine learning based COVID-19 study performance prediction
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
Spectral efficient network and resource selection model in 5G networks
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
madgavkar20181017ppt McKinsey Presentation.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Python in the browser

  • 1. Python in the Browser 01/06/2010 13:45 Python in the Browser Web Programming with Silverlight & IronPython Michael Foord [email protected] www.voidspace.org.uk @voidspace Python in the browser with Silverlight & IronPython Introduction Silverlight Say Hello to Vera Getting Started: One JS File External Python Files How it works Loading the Javascript Loading the Python Runtime The IronPython Payload Running the Python Code So we can write code... Using .NET APIs Silverlight Toolkit Try Python Questions Introduction You, the Python developer, use Python because you want to, but in the browser you use JavaScript because you think you have to. With Silverlight you can write Python code in the file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 1 of 12
  • 2. Python in the Browser 01/06/2010 13:45 browser. Silverlight Microsoft browser plugin Now installed in over 50% of browsers (riastats) Cross platform: Windows and Mac, plus Linux with Moonlight Cross browser: Safari, Firefox, IE and Chrome Runs IronPython and IronRuby Sockets, threading, local browser storage APIs Webcam access, out of browser apps IronPython docs at ironpython.net/browser/ IronPython 2.6 - the equivalent of Python 2.6. Silverlight features include: A ui system based on WPF Full access to the browser DOM Calling between Javascript and Silverlight code Out of browser applications Video, streaming media and 'deep zoom' Local browser storage Socket and threading APIs (etc) Lots more... Say Hello to Vera file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 2 of 12
  • 3. Python in the Browser 01/06/2010 13:45 Over 19000 lines of Python code (plus hundreds of lines of xaml) written over a 7 month period by two developers. Getting Started: One JS File Loading IronPython: <script src="http://gestalt.ironpython.net/dlr-latest.js" type="text/javascript"></script> Python in script tags: <script type="text/python"> def onclick(s, e): window.Alert("Hello from Python!") document.button.events.onclick += handler document.message.innerHTML = 'Hello Python!' </script> To develop a Python application in the browser, you just need your favorite text editor; so open it up, create a HTML file, reference dlr.js, and then you can use script-tags for running Python code. file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 3 of 12
  • 4. Python in the Browser 01/06/2010 13:45 External Python Files <script type="text/python" src="repl.py"></script> This creates a console when you add ?console to the url. We can reference Python files as well as inline Python. The console is hooked up to sys.stdout, so your existing text-based Python scripts can come alive in the browser (sans reading from stdin). Also, any print statements you use in the app will show up in the console as well, making it a great println-debugging tool. Let's play around with the page a bit, adding a DOM element and changing it's HTML content to "Ouch!" when clicked: >>> dir(document) [..., 'CreateElement', ...] >>> div = document.CreateElement("div") >>> div.innerHTML = "Hello from Python!" >>> document.Body.AppendChild(div) >>> div.id = "message" >>> div.SetStyleAttribute("font-size", "24px") >>> def say_ouch(o, e): ... o.innerHTML = "Ouch!" ... >>> document.message.events.onclick += say_ouch How it works file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 4 of 12
  • 5. Python in the Browser 01/06/2010 13:45 dlr.js contains a collection of functions for creating a Silverlight control on the HTML page that is capable of running IronPython code. Loading the Javascript file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 5 of 12
  • 6. Python in the Browser 01/06/2010 13:45 By default, just running dlr.js injects a Silverlight <object> tag into the page (immediately after the script-tag) so it can run only DOM-based scripts, and also scans for other script-tags indicating that you want a Silverlight rendering surface, but more on that later. Loading the Python Runtime file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 6 of 12
  • 7. Python in the Browser 01/06/2010 13:45 The injected Silverlight control points to a Silverlight application made specifically to embed the dynamic language runtime, the compiler/runtime/embedding infrastructure IronPython is built on, find all the Python code the HTML page uses, and executes it. The XAP is tiny, as the DLR and IronPython are in separate packages which are downloaded on- demand; the DLR and IronPython are not installed with Silverlight, so they must be downloaded with the application. The IronPython Payload file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 7 of 12
  • 8. Python in the Browser 01/06/2010 13:45 However, if the application depends on the ironpython.net binaries, the user's browser will cache them and they won't be re-downloaded for any other app; almost as good as being part of the installer, while still being able to be open-source. Running the Python Code file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 8 of 12
  • 9. Python in the Browser 01/06/2010 13:45 Now user-code is able to run. Each inline Python script-tag is executed as if it was one Python module, and all other Python files execute as their own modules. To allow Python to be indented inside a script tag, the margin of the first line which does not only contain whitespace is removed. Line numbers in the HTML are preserved, so error messages show up correctly. So we can write code... What about testing it? Well, Python comes batteries included. <script type="application/x-zip-compressed" src="PythonStdLib.zip"></script> <script type="text/python"> if document.QueryString.ContainsKey("test"): import sys sys.path.append("PythonStdLib") import repl repl.show() file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 9 of 12
  • 10. Python in the Browser 01/06/2010 13:45 import unittest ... That PythonStdLib.zip file contains the pieces of the Python standard-library that unittest depends on. The Python standard library is a little less than 5MB compressed, so it's not unthinkable to include the whole thing for development, but for deployment you should just include the dependencies; unittest's dependencies are 58 KB. When a zip file's filename is added to the path, it is treated like any other directory; import looks inside it to find modules. You'll also notice that import repl just worked, even though repl.py isn't in the zip file; it was referenced by a script-tag earlier. It works because script-tags actually represent file-system entries; doing open("repl.py"), or open("PythonStdLib/unittest.py") would also work. Using .NET APIs Using WritableBitmap to render fractals. Silverlight has a ton of functionality, and as I was only able to discuss a few Python libraries in Silverlight, I'll only be able to show a few Silverlight libraries being used from Python, but the entirety of Silverlight can be used from Python. See all the features Silverlight provides, as well as how to use .NET APIs in-general from Python. One interesting API is the WritableBitmap, which gives you per-pixel access to render whatever you want. For example, here its used to render a fractal. The number crunching is actually done from C#, but called from IronPython. As with any computationally-intensive operations, it's a good idea to write them in a static pre-compiled file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 10 of 12
  • 11. Python in the Browser 01/06/2010 13:45 language; for example the scientific-computation libraries for Python are actually written in C, but the library provide an API accessible to Python programmers. Unfortunately, CPython puts that responsibility on the library developer; not every C library can be directly consumed by Python code. However, this example shows that IronPython can call into any C# library, or any library written in a .NET language for that matter. This makes it trivial to just begin writing your application in Python, and then decide to convert the performance-sensitive sections to C#. We could also use the WritableBitmap to hook up to a webcam... Silverlight Toolkit silverlight.codeplex.com A rich set of user interface controls including charting components. Try Python file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 11 of 12
  • 12. Python in the Browser 01/06/2010 13:45 Questions blog.jimmy.schementi.com ironpythoninaction.com voidspace.org.uk/blog trypython.org file:///Users/michael/Dev/repository/Presentation/Talk/silverlight.html Page 12 of 12