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

标签 c# python .net python-3.x ironpython

如何在我的 C# 项目中实现需要外部模块(例如 BeautifulSoup4 和 requests)的 Python 脚本?我想在 Python 脚本中调用一个函数,但它不断向我抛出“IronPython.Runtime.Exceptions.ImportException:'没有名为 requests 的模块'”。 我没有编写任何 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");

关于c# - 如何使用 IronPython 中的包调用 Python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58193185/

相关文章:

c# - 如何在托管 C++ 中捕获非托管 C++ 异常

c# - UWP 相同的 SolidColorBrush 在 PC 和 Mobile 上是不同的

c# - 如何在 C# 中的字节数组中查找字节模式?

c# - 如何在 DLL 中捆绑 index.html、jquery.js、main.css 以在 WPF 中使用?

.net - Visual Studio : Detecting unneeded Assemblies

c# - 如何使用 mvc 6、asp.net 5 注册全局过滤器

python - 如何在 HDP 中的 zeppelin-spark2 中将库安装到 python

python - 如何渲染同一列表中的多个多边形

python socket.error 操作不允许

c# - IHostedService/BackgroundService 按计划运行(与 Task.Delay 相反)