1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Using IronPython with Python script and .Net Controller

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have followed this tutorial and it is working fine in my .Net App: https://medium.com/@hanxuyang0826/triggering-python-code-from-c-a-practical-guide-84b17d593dc6

    However, when I replace the tutorial code in MyAppPython.py

    class Calculator:
    def AddInPython(self, a, b):
    return a + b


    with some python code from OpenAI:

    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
    {
    "role": "user",
    "content": [
    {"type": "text", "text": "What's in this image?"},
    {
    "type": "image_url",
    "image_url": {
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
    },
    },
    ],
    }
    ],
    max_tokens=300,
    )

    print(response.choices[0])


    I cant get it working.

    This is my C# code after updating to try and trigger the Python file after I pasted in the OpenAI code:

    using IronPython.Hosting;
    using Microsoft.Scripting.Hosting;
    using System.Diagnostics;

    namespace MyApp.Areas.FunctionalLogic
    {
    public class IronPythonExample
    {
    public void ExecutePythonCode()
    {
    Debug.WriteLine("*****ExecutePythonCode*****");

    // Create the IronPython scripting engine
    ScriptEngine engine = Python.CreateEngine();

    // Add the directory containing the Python file to the search paths
    ICollection<string> searchPaths = engine.GetSearchPaths();
    searchPaths.Add("../MyAppPython");
    engine.SetSearchPaths(searchPaths);

    Debug.WriteLine("*****searchPath Set:" + searchPaths.ToString());

    // Import the Python file
    dynamic visionModule = engine.ImportModule("MyAppPython");

    Debug.WriteLine("*****Python file imported*****");

    // Create an instance of the Vision class
    dynamic vision = visionModule();

    Debug.WriteLine("*****Instance Created*****");

    // Call the MyAppPython method
    vision();

    }
    }
    }


    It seems to be ok down as far as here, then throws an exception:

    Debug.WriteLine("*****searchPath Set:" + searchPaths.ToString());


    .

    Exception thrown: 'IronPython.Runtime.Exceptions.ImportException' in Microsoft.Dynamic.dll


    I have been going in circles with this trying different variations. Does anyone have any suggestions?

    Continue reading...

Compartilhe esta Página