[IronPython] IronPython like Jython

Larry O'Brien lobrien at knowing.net
Thu Dec 16 02:42:16 CET 2004


>>Python from .NET apps (at least C#). For me the 
>>most important is the second. It needs not to be a production
>>implementation. I need only a few hits because reading all the code of 

Chris,

I have an article coming out on DevX talking about driving IronPython with
the Tablet PC. Maybe the following will help. Ignore the OutputQueue --
that's a class that I wrote to capture output, and remove the lines
referring to UnparseableStatement -- that's a class that I wrote as well.
The methods marked [test] are lifted out of an NUnit class.  

I'd be happy to share more with you or anyone else if it's helpful.

Cheers,
Larry O'Brien
http://www.knowing.net/


--

using System;
using IronPython.AST;
using IronPython.Modules;
using IronPython.Objects;

namespace Pynk.Wrapper
{
	public class FrameHolder
	{
		public FrameHolder()
		{
			q = new OutputQueue();			
			sys.path.append(Environment.CurrentDirectory);
			sys.stdout = q.pythonOut;

			top = new module();
			topFrame = new Frame(top);
		}

		OutputQueue q;
		module top;
		Frame topFrame;
		Frame Frame
		{
			get { return topFrame; }
		}

		public Stmt Parse(string s)
		{
			Parser p = Parser.fromString(s);
			try
			{
				Stmt statement = p.parseStmt();
				return statement;
			}
			catch(Exception ex)
			{
				return new UnparseableStatement(ex);
			}
		}

		public string Run(Stmt s)
		{
			FrameCode code = SnippetMaker.generate(s, "input");
			code.Run(topFrame);
			string results = q.ReadToEnd();
			return results;
		}

		public string ParseAndRun(string s)
		{
			Stmt stmt = Parse(s);
			if(stmt.GetType() != typeof(UnparseableStatement))
			{
				string results = Run(stmt);
				return results;
			}
			else
			{
				return "";
			}
		}

	}
}

--
[Test]
		public void TestCreateVariable()
		{
			FrameHolder fh = new FrameHolder();
			string s = "b = 2+2";
			string results = fh.ParseAndRun(s);
			string r2 = fh.ParseAndRun("b");
			Assert.AreEqual("4\n",r2);
		}

		[Test]
		public void TestBlock()
		{
			FrameHolder fh = new FrameHolder();
			string block = "b = [\"Dave\", \"Mark\", \"Ann\",
\"Phil\"]";
			string results = fh.ParseAndRun(block);
			block = "for name in b:\n";
			block += "\tprint name\n";
			string results2 = fh.ParseAndRun(block);
			Assert.AreEqual("Dave\nMark\nAnn\nPhil\n",results2);
		}

		[Test]
		public void AnonVariable()
		{
			FrameHolder fh =new FrameHolder();
			string block = "2+2";
			string results = fh.ParseAndRun(block);
			block = "_ * 2";
			string r2 = fh.ParseAndRun(block);
			Assert.AreEqual("8\n",r2);
		}





More information about the Ironpython-users mailing list