当我尝试使用IronPython参考在C#代码中使用python脚本时,Execute方法不起作用?

问题描述

我对C#还是很陌生,我正试图用它在python代码中执行我的算法。

问题出在source.Execute()说>> >> Microsoft.Scripting.SyntaxErrorException:'无效的语法' 。我已经检查了几个小时,但仍然找不到任何似乎是导致问题的原因。这是代码

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace DeliveryManager
{

public partial class Form1 : Form
{
    // Class Names
    public string DeliveryObject = "DeliveryRequest";
    public string DeliveryManagerObject = "DeliveryManager";

    // Directory
    public string ScriptingSource = "D:\\VISUAL STUdio PROJECTS\\PROJECT OOP\\DeliveryClass.py";

    // Scripting Engine 
    ScriptEngine engine = Python.CreateEngine();
    
    
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender,EventArgs e)
    {

        string loc = textBox1.Text;
        float travelVal = float.Parse(textBox2.Text);

        // Getting the Python Script
        ScriptSource source = engine.CreateScriptSourceFromFile(ScriptingSource);
        ScriptScope scope = engine.CreateScope();
        source.Execute(scope);

        // Getting Python Classes
        dynamic DeliveryRequestClass = scope.Getvariable(DeliveryObject);


        // Instantiating Classes
        dynamic DelvReq = DeliveryRequestClass();

        // Object List
        var deliveryList = new List<object>();

        deliveryList.Add(DelvReq(loc,travelVal));

        Console.WriteLine(deliveryList);
    }
}

}

这是python代码

class DeliveryRequest:
    def __init__(self,travelValue,travelName):
        self.travelValue = travelValue
        self.travelName = travelName
        self.pv = None

    def __repr__(self):
        return f"val:{self.travelValue} loc: {self.travelName}"

基本上,我想做的是在Windows窗体中每按一次按钮,将DeliveryRequest Objects添加到C#列表中,然后打印出来。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)