You are viewing drifter46and2

.. .:.:: ::. .:.:..
February 2007
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28

Old Code

Well I decided to post some old code I am currently not using.. Might be interesting to some ironpython users. Currently since working fulltime as c# developer my personal programming has decreased enormously. Less reason to code at home, more time to play guild wars.

Embed cs file will compile code to dll, then allow you to import it.. currently does no checking to see if dll exists or cs has changed. Below that is an example which shows how to use this..

"""Class to compile and import csharp code embedded inside of a python module."""

from System.CodeDom import Compiler
from Microsoft.CSharp import CSharpCodeProvider
import clr

class embedcs(object):
"""Setup variables for use internally. The dll will inherit name that is passed.
Recommend setting this to be the same as the namespace of the c# file."""

def __init__(self,name,references,code):
self.Name = name
if references is None:
self.References = []
self.References = references
self.Code = code
self.Errors =[]
self.CompilerParams = None
self.Assembly = None
self.Namespace = None

def setupparams(self):
"""These are the parameters passed which tells it to create a dll as well
as to generate file vs. memory and add any references used."""

self.CompilerParams = Compiler.CompilerParameters()
self.CompilerParams.OutputAssembly = self.Name + ".dll"
self.CompilerParams.GenerateInMemory = False
self.CompilerParams.TreatWarningsAsErrors = False
self.CompilerParams.GenerateExecutable = False
for reference in self.References:

def compilecs(self):
"""Compiles the actual c# code, if there are any errors sets your assembly to None,
otherwise will return the path to the assembly. Also appends errors to error list."""

provider = CSharpCodeProvider()
compile = provider.CompileAssemblyFromSource(self.CompilerParams, self.Code)
if compile.Errors.HasErrors:
self.Assembly = None
self.Errors = [error for error in compile.Errors.List]
self.Assembly = compile.PathToAssembly

def loadmodule(self):
"""Loads the dll created and then imports the module to the Namespace attribute"""

assert self.Assembly is not None, self.Errors
self.Namespace = __import__(self.Name)

def main(self):
"""Calls all methods necessary to create the dll and return the module."""

from embedCS import embedcs

code = """using System;
namespace hello
public class HelloWorld


public static void Main()

Console.WriteLine("Hello World!");

#references = []
name = "hello"
cs = embedcs(name, None, code)
hello = cs.Namespace

Next example is an example of ironpython command shell embedded in window textbox. It works for everything but input/raw_input.. I never found a good solution for handling standard in, inside a textbox.
import sys
import codeop

class fakefile(object):
def __init__(self): = ""

def retrieve(self):
stor = None
if != "":
stor =[:-1] = ""
return stor

def write(self, args): += args

filename = "<input ... >"
cprt = 'Type :help", "copyright", "credits" or "license" for more information.'
banner = "%s" % sys.version

buffer = ""
more = 0

#in_std = fakefilein()
out_std = fakefile()
err_std = fakefile()

#sys.stdin = in_std
sys.stdout = out_std
sys.stderr = err_std
locals = {"Name":"Console","__doc__":None}

def doit(source):
global buffer
global more
text = ""
print more

if more:
buffer += source
if runsource(buffer):
text += sys.ps2
return text

if not more:
if runsource(source):
more = 1
text += sys.ps2
return text
more = 0
buffer = ""
if != "":
text += out_std.retrieve() + "\r\n"
if != "":
text += err_std.retrieve() + "\r\n"
text += sys.ps1
return text

def compile_exec(source, locals):
exec source in locals
except SystemExit:
ex_type, exc, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
print "Traceback (most recent call last): \r\n \
%s, line %i, in %s \r\n%s: %s" % (co.co_filename,lineno,co.co_name,ex_type.__name__,exc)

def runsource(source):
code = codeop.compile_command(source)
except (OverflowError, SyntaxError, ValueError):
print "Runtime Error"
return False
if code is None:
return True

compile_exec(code, locals)
return False
import clr
from System import Drawing
from System.Windows import Forms
import sys
import utils
#from winconsole import winconsole

class textBox(Forms.TextBox):
def __init__(self):
self.Dock = Forms.DockStyle.Fill
self.Multiline = True
self.ScrollBars = Forms.ScrollBars.Both
self.Size = Drawing.Size(320,400)
self.text = utils.banner + "\r\n" + sys.ps1
self.Text = self.text
self.SelectionStart = self.TextLength
self.caretstart = self.TextLength

def OnKeyDown(self, keys):
if keys.KeyCode == Forms.Keys.Return:
self.SelectionLength = 0
self.SelectionStart = self.caretstart
selected = self.TextLength - self.SelectionStart
self.SelectionLength = selected
bleh = self.SelectedText
self.text += bleh
self.SelectedText = ""
self.text += "\r\n" + utils.doit(bleh + '\n')
self.Text = self.text
self.SelectionStart = self.TextLength
self.caretstart = self.SelectionStart

if self.SelectionStart < self.caretstart:
self.SelectionStart = self.caretstart

def OnKeyPress(self, keys):
if keys.KeyChar == '\r':
keys.Handled = True

class newform(Forms.Form):
def __init__(self):
self.Text = "IronPython"
self.ClientSize = Drawing.Size(640, 480)

teh = newform()

I hope someone finds this code useful. Currently debating on playing with cherrypy 3.0 and mochikit. I do have some old code that is an example of using cheetah with twisted web, which I adapted from someone elses code I found on internet. I will post that another time.

Current Mood: apatheticapathetic