使用资源将Python嵌入到C#中

2024-05-16 02:10:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为一个问题工作了一段时间,现在我似乎无法解决,所以我需要一些帮助!问题是我正在用C编写一个程序,但我需要一个来自我创建的Python文件的函数。这本身没有问题:

...Usual Stuff

using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting; 

namespace Program
{
    public partial class Form1 : Form
    {
        Microsoft.Scripting.Hosting.ScriptEngine py;
        Microsoft.Scripting.Hosting.ScriptScope s;
        public Form1()
        {
            InitializeComponent();

            py = Python.CreateEngine(); // allow us to run ironpython programs
            s = py.CreateScope(); // you need this to get the variables

        }

        private void doPython()
        {
            //Step 1: 
            //Creating a new script runtime             
            var ironPythonRuntime = Python.CreateRuntime();

            //Step 2:
            //Load the Iron Python file/script into the memory
            //Should be resolve at runtime
             dynamic loadIPython = ironPythonRuntime.;

             //Step 3:
             //Invoke the method and print the result
             double n = loadIPython.add(100, 200);
             numericUpDown1.Value = (decimal)n;
         }
    }
}

但是,这要求文件“first.py”位于程序编译后的任何位置。因此,如果我想共享我的程序,我将不得不发送可执行文件和python文件,这是非常不方便的。我想解决这个问题的一个方法是将“first.py”文件添加到资源中并从那里运行。。。但我不知道怎么做,甚至不知道是否有可能。

当然,上面的代码对此不起作用,因为.UseFile方法接受字符串参数而不是byte[]。有人知道我会怎样进步吗?


Tags: 文件thetopy程序stepscriptpublic