1

I want to get a variable from my Python file and write it in the console here is what i have tried:

main.py

myVar = "Hello There"

program.cs

using System;
using IronPython.Hosting;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var py = Python.CreateEngine();

            var pythonVariable = py.ExecuteFile("main.py");
            Console.WriteLine(pythonVariable);

            Console.Read();

        }
    }
}

I would expect the output to be 'Hello There' but I get this: 'Microsoft.Scripting.Hosting.ScriptScope'

1
  • Should you be printing the variable in the main.py? There is no output from that script Commented Dec 27, 2019 at 22:58

2 Answers 2

1

The output you get is hinting what you have to look for. ExecuteFile returns a ScriptScope which contains all the variables defined in the executed Python code.

In order to retrieve a specific variable from it you need to use GetVariable or TryGetVariable (if the variable may not exist in the file), e.g.:

using System;
using IronPython.Hosting;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var py = Python.CreateEngine();

            var pythonVariable = py.ExecuteFile("main.py").GetVariable<string>("myVar");
            Console.WriteLine(pythonVariable);

            Console.Read();

        }
    }
}

Note that I used the generic version of GetVariable to convert it to a string immediately. The non-generic version returns a dynamic object, choosing which one you need depends on how you intend to use the variable

Sign up to request clarification or add additional context in comments.

Comments

0

Follow this procedure and it should work, Be sure to have file in the right place. I don't see you setting any variables Do that and just follow the code:

var engine = Python.CreateEngine(); // Extract Python language engine from their grasp
            var source = engine.CreateScriptSourceFromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "myPython.py"));
            var scope = engine.CreateScope();
            source.Execute(scope);
            var theVar = scope.GetVariable("myVar");

            Console.WriteLine(theVar);
            Console.ReadKey();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.