简体   繁体   中英

IronPython 'execfile' Equivalent in C#

Id like to know how to perform the functionality of the 'execfile' Python command but from C# . 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:

execfile('header.py')

I would like to make that execfile from C# , how can I do that?

Note: Import does not work because i'm declaring variables dynamically inside header.py scope. import would not import that variables because they do not exist yet.

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. 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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