问题
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
回答1:
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
).
回答2:
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());
来源:https://stackoverflow.com/questions/21737913/ironpython-changing-behaviour-of-sourcecodekind-interactivecode