| drifter46and2 ( @ 2007-02-04 22:29:00 |
| Current mood: |
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..
embedCS.py
------------------------
"""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 = []
else:
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.TreatWarningsAsError
self.CompilerParams.GenerateExecutable = False
for reference in self.References:
self.CompilerParams.ReferenceAssemblies.A
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.C
if compile.Errors.HasErrors:
self.Assembly = None
self.Errors = [error for error in compile.Errors.List]
else:
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
clr.AddReferenceToFile(self.Assembly)
self.Namespace = __import__(self.Name)
def main(self):
"""Calls all methods necessary to create the dll and return the module."""
self.setupparams()
self.compilecs()
self.loadmodule()
cstest.py
---------------------
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)
cs.main()
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.
utils.py
------------------------
import sys
import codeop
class fakefile(object):
def __init__(self):
self.storage = ""
def retrieve(self):
stor = None
if self.storage != "":
stor = self.storage[:-1]
self.storage = ""
return stor
def write(self, args):
self.storage += 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 out_std.storage != "":
text += out_std.retrieve() + "\r\n"
if err_std.storage != "":
text += err_std.retrieve() + "\r\n"
text += sys.ps1
return text
def compile_exec(source, locals):
try:
exec source in locals
except SystemExit:
raise
except:
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_typ
def runsource(source):
try:
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
shellapp.py
----------------------------
import clr
clr.AddReferenceByPartialName("System.Wi
clr.AddReferenceByPartialName("System.Dr
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
self.ScrollToCaret()
else:
if self.SelectionStart < self.caretstart:
self.SelectionStart = self.caretstart
self.ScrollToCaret()
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)
self.Controls.Add(textBox())
teh = newform()
Forms.Application.Run(teh)
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.