简体   繁体   English

在C#中等效的IronPython'execfile'

[英]IronPython 'execfile' Equivalent in C#

Id like to know how to perform the functionality of the 'execfile' Python command but from C# . 我想知道如何从C#执行execfile Python命令的功能。 In this example: 在此示例中:

var runtime = Python.CreateRuntime();
dynamic scope = Python.UseFile("body.py");

you specify the body file. 您指定主体文件。

In the header of body.py , I specify the header: body.py的标头中,指定标头:

execfile('header.py')

I would like to make that execfile from C# , how can I do that? 我想从C#创建该execfile,我该怎么做?

Note: Import does not work because i'm declaring variables dynamically inside header.py scope. 注意:导入不起作用,因为我在header.py范围内动态声明变量。 import would not import that variables because they do not exist yet. import不会导入该变量,因为它们尚不存在。

Thank you very much! 非常感谢你!

If you want different behaviour from the exec file you can easily create your own and do things like this (share scope) by creating the function in .NET and set this to the scope. 如果您想要与exec文件不同的行为,则可以通过在.NET中创建函数并将其设置为作用域来轻松创建自己的行为并执行类似的操作(共享作用域)。 This would also allow you to add additional functionality if you wish. 如果需要,这还允许您添加其他功能。

This seems to work: 这似乎可行:

Setting up the engine: 设置引擎:

var py = Python.CreateEngine();
var source = py.CreateScriptSourceFromFile(@"..\..\IronPython\body.py");
var scope = py.CreateScope();

Then I create the function that can be used by scripts and set it on the scope 然后,我创建脚本可以使用的函数并将其设置在作用域上

Action<string> execFileCallback = fileName =>
{
    var s2 = py.CreateScriptSourceFromFile(fileName);
    s2.Execute(scope);
};
((dynamic)scope).myexecfile = execFileCallback;
source.Execute(scope);

Now my Body.py looks like this: 现在我的Body.py看起来像这样:

someVarSetByBody = "This was set by the body"
Console.WriteLine("Body is loading")
myexecfile(r"..\..\IronPython\Header.py")
Console.WriteLine("Body has loaded")

And my Header.py Looks like this: 我的Header.py看起来像这样:

Console.WriteLine("Header is loading")
Console.WriteLine("Variable set by body: %s" %  someVarSetByBody)
Console.WriteLine("Header has loaded")

It is now able to use the same scope in the different scripts so you can share the variables. 现在,它可以在不同的脚本中使用相同的作用域,因此您可以共享变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM