简体   繁体   English

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

[英]How to get a variable from Python file using IronPython

I want to get a variable from my Python file and write it in the console here is what i have tried:我想从我的 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();

        }
    }
}

I would expect the output to be 'Hello There' but I get this: 'Microsoft.Scripting.Hosting.ScriptScope'我希望输出是“你好”,但我得到了这个:“Microsoft.Scripting.Hosting.ScriptScope”

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. ExecuteFile返回一个ScriptScope ,其中包含在执行的 Python 代码中定义的所有变量。

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), eg:为了从中检索特定变量,您需要使用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();

        }
    }
}

Note that I used the generic version of GetVariable to convert it to a string immediately.请注意,我使用了通用版本的GetVariable立即将其转换为string The non-generic version returns a dynamic object, choosing which one you need depends on how you intend to use the variable非泛型版本返回一个dynamic对象,选择您需要的对象取决于您打算如何使用该变量

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

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

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