0

I'm using PythonNet to call a Python script from within a C# code.

I would like to define a module in a string variable (like myModule in the code below) and to be able to import that module and use its functions later:

    using (Py.GIL())
    {
        // create a Python scope
        using (PyScope scope = Py.CreateScope())
        {
            string myModule = @"# a lot of fancy Python code"; // Define a module here

            // Here I'd like to register myModule as a module,
            // to be used later within this scope: what shall I do?

            string script = @"import myModule as functions";   // import and use the module here
            scope.Exec(script);
            ...
            string s = scope.Eval<string>(...);
            return s;
        }
    }

How can this be achieved?

Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66

1 Answers1

0

The PyScope class defines an overload of Import that accepts a PyScope and a string as parameters.

First, execute your module in a scope (moduleScope), then you can import it in a second scope

            using (PyScope moduleScope = Py.CreateScope())
            {
                string myModule = @"# a lot of fancy Python code"; // Define a module here
                moduleScope.Exec(myModule);

                // create a Python scope
                using (PyScope scope = Py.CreateScope())
                {
                    scope.Import(moduleScope, "functions");

                    double d = scope.Eval<double>("functions.my_variable");
                    ...
Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66