问题描述
我可以使用以下命令在C#中执行IronPython:
I can execute IronPython in C# with:
ScriptSource Source = PyEngine.CreateScriptSourceFromString(Code, SourceCodeKind.InteractiveCode);
CompiledCode Compiled = Source.Compile();
Compiled.Execute(PyScope);
这意味着我可以先执行A=1
,然后执行A
.然后将输出1
.
This means that I can execute A=1
and then A
. This will then output 1
.
是否有一种方法可以覆盖此行为,以便在打印前将A
重定向到C#函数,例如CustomPrinter
?我知道我可以按照 https://stackoverflow.com/a/13871861/1447657但我认为应该有更好的方法.
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.
编辑1
感谢您的回答,但我对自己的目标还不太清楚.
Thanks for your answers but I was slightly unclear about my aims.
我知道我可以使用PyEngine.Runtime.IO.SetOutput(stream, encoding)
重定向输出,但是我希望在将其转换为字符串之前检索输出值.因此,如果收到的是A=[1,2,3]
IronPython.Runtime.List
而不是string
.
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.
我不确定在不更改IronPython源代码或不使用正则表达式在CustomPrinter.Write
函数中自行包装变量(例如A
)的情况下是否可能实现
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
推荐答案
您可以PyEngine.Runtime.IO.SetOutput(stream, encoding)
将要转到stdout
的内容定向到自定义流(另请参见.SetErrorOutput
和.SetInput
). stdin
).
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
).
这篇关于IronPython:更改SourceCodeKind.InteractiveCode的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!