1

I create a .NET application and I want to execute python code from it. In this case I want to create a new file when pressing a button by calling the "run" function in my python file. However the code throws me an exception when I try to import libraries like: os, pandas, tensorflow, etc., in my python script.

The exception is: IronPython.Runtime.Exceptions.ImportException: 'No module named os' (in this case for the os library, and similar things happen with other libraries).

How I can correctly tell Iron Python to install the libraries before running the python script?

I have already seen this post: IronPython cannot import module "os", and also this one: IronPython cannot import module os. However, neither of those shows how to execute a specific function and pass the arguments. Also, I have trouble in the first solution because Iron Python is not installed in my program files. Also both solutions don't show how to install other libraries like tensorflow or pandas.

My C# code is:

public partial class App : Form
{
    public App()
    {
        InitializeComponent();
    }

    static string pythonPath = @"C:\Users\Someone\Documents\main.py";
    static ScriptRuntime python = Python.CreateRuntime();
    dynamic script = python.UseFile(pythonPath);
    
    private void button_Click(object sender, EventArgs e)
    {
     string name = "Monica";
        script.run(name);
    }
    
}

Then my python code (the main.py file) is:

import os  # The line that throws the exception!!!
path = os.path.dirname(__file__)

def run(name):
   f = open(path + "demofile.txt", "w")
   f.write("Hello", name)
   f.close()
2
  • Welcome to Stack Overflow. For future reference, please note that you are expected to make some attempt to solve the problem yourself first, in particular by looking for a solution. I found the linked duplicate (and many other possibly useful resources) as the third result by putting ironpython import into a search engine. It really is that easy. Commented Oct 15, 2021 at 10:07
  • If you have not solved this, the first step is to attempt what the links say to do. In stackoverflow.com/a/18000650/199364, it says to add line sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib') before import os. Try that (adjusting path to where your libraries are installed), and edit your question to show what you've tried, and what happened. If the other packages are in same location, you will also be able to do import pandas, etc. Commented Nov 1, 2021 at 6:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.