问题描述
我正在使用Python.net从我的C#应用程序中调用Python脚本。第一次从C#运行Python脚本时,一切工作一切顺利,但每次之后,我都会收到导入错误ModuleNotFoundError: No module name 'Part'
。 FreeCAD
,Part
,BOPTools.JoinAPI
的导入均为空,仅在连续运行中。
Python脚本:
def export_toStep(ribs,freeCAD_path,file_path,file_name):
try:
import sys
sys.path.append(freeCAD_path)
import FreeCAD
import Part
import BOPTools.JoinAPI as joinAPI
rib_curves = []
for rib in ribs:
rib_curves.append(Part.BSplineCurve(rib))
wing_sections = []
for i in range(0,len(rib_curves) - 1,1):
wing_sections.append(Part.makeLoft([rib_curves[i].toShape(),rib_curves[i + 1].toShape()],True))
wing = joinAPI.connect(wing_sections,tolerance=0.0)
wing.exportStep(file_path + "/" + file_name)
except Exception as ex:
raise ex
C#
using (Py.GIL())
{
try
{
var ribs = AirfoilsToPythonnet(airfoils);
dynamic IOTools = Py.Import("IOTools");
IOTools.export_toStep(ribs,freeCAdpath,tempFilePath,fileName);
}
catch (PythonException error)
{
// Log error
}
}
PythonEngine.Shutdown();
不确定是什么原因导致的,Python函数的所有输入都相同(我检查以确保没有古怪的事情发生)。
以下是有关我在做什么的其他信息。
Python and .Net Integration options
pythonnet Embedding Python in .net example failing to load module
更新
能够通过将模块作为参数传递给Python函数并删除Python脚本中的导入来解决此问题。
新的C#代码:
using (Py.GIL())
{
try
{
var ribs = AirfoilsToPythonnet(airfoils);
dynamic IOTools = Py.Import("IOTools");
dynamic FreeCAD = Py.Import("FreeCAD");
dynamic Part = Py.Import("Part");
dynamic JoinAPI = Py.Import("BOPTools.JoinAPI");
IOTools.export_toStep(Part,JoinAPI,ribs,fileName);
}
catch (PythonException error)
{
// Log error
throw error;
}
}
PythonEngine.Shutdown();
但是,这还不是全部。这只像以前一样在第一次执行时起作用,但是将Part
和BOPTools.JoinAPI
模块的路径添加到PYTHONHOME环境变量解决了该问题。
仍不确定为什么它会在第一次执行时起作用,但不能在连续执行时起作用。我注意到,当我在C#中导入模块时,FreeCAD
模块正在加载良好,尽管它是内置模块(在连续执行时)而不是从环境中指定的路径(首次执行时)加载,不知道为什么);但是,找不到Part
和BOPTools.JoinAPI
模块。 有关环境路径的更多信息,请参见上面的第二个链接。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)