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()
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Monica
  • 11
  • 3
  • Welcome to Stack Overflow. For future reference, please note that [you are expected](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) 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](https://duckduckgo.com/?q=ironpython+import). It really is that easy. – Karl Knechtel Oct 15 '21 at 10:07
  • If you have not solved this, the first step is to attempt what the links say to do. In https://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. – ToolmakerSteve Nov 01 '21 at 06:22

0 Answers0