简体   繁体   English

使用 Pythonnet 从 C# 调用 Python 会引发导入错误

[英]Calling Python from C# using Pythonnet throws import error

I have a use case where I want to be able to call a function which is written in Python from my C# code base.我有一个用例,我希望能够从我的 C# 代码库调用一个用 Python 编写的函数。 When I make a call to this function I want to be able to pass C# types(custom classes) to Python function and for that I was exploring pythonnet .当我调用此函数时,我希望能够将 C# 类型(自定义类)传递给 Python 函数,为此我正在探索pythonnet

Python project has a following sample structure - Python 项目具有以下示例结构 -

main.py
service1.py

main.py has the main function which calls the methods exposed by service1.py - main.py具有调用service1.py公开的方法的主要功能 -

from Service1 import MyService1

def Run(a, b):
   service1 = MyService1()
   service1.method(a, b)

Now from C# side when I try to execute the Python it is throwing error -现在从 C# 端,当我尝试执行 Python 时它抛出错误 -

Python.Runtime.PythonException: 'No module named 'Service1'' Python.Runtime.PythonException:“没有名为‘Service1’的模块”

C# code - C#代码-

Runtime.PythonDLL = @"C:\Program Files\Python39\Python39.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
  using (var scope = Py.CreateScope())
  {
     scope.Exec(File.ReadAllText(@"..\Python\main.py"));
   }
 }

How do I need to import the required classes correctly?我需要如何正确导入所需的类?

I was running into this issue because my Python scripts were not part of the build folder.我遇到这个问题是因为我的 Python 脚本不是构建文件夹的一部分。 I had to ensure that the required Python files are part of the build folder on the successful build of the solution.我必须确保所需的 Python 文件是成功构建解决方案时构建文件夹的一部分。

To make a file part of your build folder you will need to - Right click on file in VS -> Properties -> Copy To Output directory -> select Copy Always or Copy if newer.要使文件成为构建文件夹的一部分,您需要 - 在 VS 中右键单击文件 -> 属性 -> 复制到输出目录 -> 选择始终复制或如果较新则复制。

Alternatively, you can do this from.csproj file as well.或者,您也可以从 .csproj 文件执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM