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!
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");