1

How would I come to implementing a Python script that requires external modules (such as BeautifulSoup4 and requests) in my C# project? I want to call a function in the Python script but it keeps throwing me a "IronPython.Runtime.Exceptions.ImportException: 'No module named requests'". I do not have any IronPython script written because I'm using a Python script that was made from another user. I have a virtual environment set up with Python to import the necessary modules.

I have no idea where to approach this. I've looked on multiple sites but they all require me to write an IronPython script. Are there no other options to calling functions other than setting up the necessary script?

C# Code:

        static dynamic pythonFile;
        static void Main(string[] args)
        {
            // Loading Python file
            var ipy = Python.CreateRuntime();
            pythonFile = ipy.UseFile("test.py"); //throws error when this launches.

            DisplayMain();

            Console.ReadKey();
        }

Python Code (small snippet for example):

import requests

def get_stock(stock_name, price_metric):
    print(stock_name + " " + price_metric)

def get_industry_indicators(startTime, endTime):
    print(startTime + " " + endTime)

def get_market_cap(industry, startTime, endTime):
    print(industry + " " + startTime + " " + endTime)

def get_headers(link):
    print(requests.get(link))

I want to be able to call my python function (get_headers) and pass in a link and then have it print on my C# Console. Please help!

4
  • Although it is a Japanese article, it has been written about the same topic recently, so please refer to it using web translation etc. .NET (on Windows)からpythonを呼び出す
    – kunif
    Commented Oct 1, 2019 at 23:08
  • @kunif following the guide's concepts and making my own modifications, I have came to a different error which is "no module named future". Any ideas on that?
    – Brandon
    Commented Oct 2, 2019 at 1:39
  • I do not have any information related to the error and name. If you add what you have done, all the stack trace displayed in error, and the appropriate source line in the trace, you will get a better answer.
    – kunif
    Commented Oct 2, 2019 at 2:10
  • @kunif I found the error. Thank you.
    – Brandon
    Commented Oct 2, 2019 at 2:19

1 Answer 1

4

I found the error. Search paths for the needed modules must be included. Here is an example.

            var engine = Python.CreateEngine();
            var searchPaths = new List<string>();
            searchPaths.Add(AppDomain.CurrentDomain.BaseDirectory + @"\Lib\site-packages");
            searchPaths.Add(@"C:\...\projectName\Lib\");
            engine.SetSearchPaths(searchPaths);

            engine.ExecuteFile("test.py");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.