如何使用 IronPython 从 Python 文件中获取变量

How to get a variable from Python file using IronPython

我想从我的 Python 文件中获取一个变量并将其写入控制台 这是我尝试过的:

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();

        }
    }
}

我希望输出为 'Hello There' 但我得到了这个:'Microsoft.Scripting.Hosting.ScriptScope'

您得到的输出提示您必须查找的内容。 ExecuteFile returns 一个 ScriptScope 包含在执行的 Python 代码中定义的所有变量。

为了从中检索特定变量,您需要使用 GetVariableTryGetVariable(如果文件中可能不存在该变量),例如:

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();

        }
    }
}

请注意,我使用 GetVariable 的通用版本立即将其转换为 string。非泛型版本returns一个dynamic对象,选择你需要的取决于你打算如何使用变量

按照此过程进行操作,它应该可以工作,确保文件位于正确的位置。我没有看到你设置任何变量这样做并遵循代码:

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();