2

I can execute IronPython in C# with:

ScriptSource Source = PyEngine.CreateScriptSourceFromString(Code, SourceCodeKind.InteractiveCode);
CompiledCode Compiled = Source.Compile();
Compiled.Execute(PyScope);

This means that I can execute A=1 and then A. This will then output 1.

Is there a way I can override this behaviour so A will be redirected to a C# function, say CustomPrinter before printing? I know I can 'overload' the print function as described by https://stackoverflow.com/a/13871861/1447657 but I feel there should be a better way.

Edit 1

Thanks for your answers but I was slightly unclear about my aims.

I know I can redirect output with PyEngine.Runtime.IO.SetOutput(stream, encoding) but I wish to retrieve the output value before it has been cast to a string. So if A=[1,2,3] IronPython.Runtime.List instead of a string is recieved.

I'm not sure if this is even possible without changing the IronPython source code or using a Regex to wrap variables on their own (like A) in the CustomPrinter.Write function

Community
  • 1
  • 1
Jonathan
  • 585
  • 7
  • 27
  • 1
    After Edit 1: Is there any reason to avoid using `SourceCodeKind.Expression`? – Pawel Jasinski Feb 15 '14 at 13:18
  • @PawelJasinski Thanks, I hadn't realised what that did. I Googled it and came across http://stackoverflow.com/questions/1966421/get-last-statement-result-in-embedded-ironpython-v2 which is effectivly what I wanted to do. I'm now just doing `object Result = Compiled.Execute(PyScope);` which works perfectly. – Jonathan Feb 15 '14 at 15:46

2 Answers2

2

You can PyEngine.Runtime.IO.SetOutput(stream, encoding) to direct what would go to stdout to a custom stream (see also .SetErrorOutput for stderr and .SetInput for stdin).

Jeff Hardy
  • 7,632
  • 24
  • 24
0

you can implement file object (in this case you need only write method accepting string) and assign it to sys.stdout.

public class PythonFile {
    public void write(string s) {
    }
}

and later:

PyEngine.GetSysModule().SetVariable("stdout", new PythonFile());
Pawel Jasinski
  • 796
  • 3
  • 10