如何使用IronPython的软件包调用Python脚本? - c#

我该如何在C#项目中实现需要外部模块(例如BeautifulSoup4和请求)的Python脚本?我想在Python脚本中调用一个函数,但它一直使我抛出“ IronPython.Runtime.Exceptions.ImportException:'没有命名为请求的模块'”。
我没有编写任何IronPython脚本,因为我使用的是由其他用户制作的Python脚本。我使用Python设置了一个虚拟环境,以导入必要的模块。

我不知道该在哪里处理。我看过多个站点,但它们都需要我编写IronPython脚本。除了设置必要的脚本以外,没有其他选择来调用函数吗?

C#代码:

        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代码(例如小片段):

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))

我希望能够调用我的python函数(get_headers)并传递一个链接,然后将其打印在我的C#控制台上。请帮忙!

参考方案

我发现了错误。必须包括所需模块的搜索路径。这是一个例子。

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

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何在python中将从PDF提取的文本格式化为json - python

我已经使用pyPDF2提取了一些文本格式的发票PDF。我想将此文本文件转换为仅包含重要关键字和令牌的json文件。输出应该是这样的:#PurchaseOrder {"doctype":"PO", "orderingcompany":"Demo Company", "su…