Fabien Meghazi wrote:
> How can I execute some python code that I have in a String() from a C#
> .NET
> program or an aspx application ?
> I also would like to get back the stdout that the python code
produced.

You want to use IronPython.Hosting.PythonEngine.  Here's a simple
example program.  We're very interested in feedback on experiences with
hosting IronPython from other .NET languages as that's an important
scenario, but not one that I have much personal experience with.

Does this give you what you're looking for? - Jim

----------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using IronPython.Hosting;

namespace HostingDemo {
    class Program {
        static void Main(string[] args) {
            PythonEngine engine = new PythonEngine();

            // evaluating a Python expression to get an object back
            string expr = "2+2";
            Console.WriteLine("{0} = {1}", expr, engine.Evaluate(expr));

            // executing a chunk of Python code
            string stmt = "for i in range(6):\n\tprint '***'*(i+1)";
            engine.Execute(stmt);

            // exposing variables to Python code
            Program p = new Program();
            engine.SetVariable("app", p);
            string s =
(string)engine.Evaluate("app.GetImportantString()");
            Debug.Assert(s == p.GetImportantString());

            // capturing stdout - this should be much cleaner
            // using code outside of IronPython.Hosting will be much
less 
            // stable than code inside of IronPython.Hosting
            OutputCollector output = new OutputCollector();
            IronPython.Modules.sys.stdout = output;
            engine.Execute(stmt);
            string result = output.buffer.ToString();
            Console.WriteLine("got string of length {0}",
result.Length);
 
Console.WriteLine(IronPython.Objects.StringOps.Quote(result));
        }

        public string GetImportantString() {
            return "ni";
        }

        // A quick hack, not the ideal framework design
        class OutputCollector {
            public StringBuilder buffer = new StringBuilder();

            public bool softspace = false; // weird Python print feature
            public void write(string data) {
                buffer.Append(data);
            }
        }
    }
}
_______________________________________________
users-ironpython.com mailing list
users-ironpython.com@lists.ironpython.com
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com

Reply via email to