Pythonnet으로 코드를 작성할 때 가장 불만인 부분은 아무래도 기존의 C# 코드와 결이 맞지 않게 작성할 수 밖에 없다는 점입니다. 그런데 FBA 덕분에 기존 프로젝트 코드를 침범하거나, 힘들게 통합하지 않고 Python 특유의 스크립트 코드를 그대로 존중하면서 독립된 코드를 작성할 수 있게 되는 점은 정말 훌륭합니다.
Python DLL을 찾아주는 부분만 정확히 처리할 수 있다면, 아래와 같이 Bootstrapper 코드를 자연스럽게 만들 수 있어 매우 유용한 것 같습니다.
#:package pythonnet@3.0.5
#:property PublishAot=False
using Python.Runtime;
var versionPostfix = "312";
Runtime.PythonDLL = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@$"Programs\Python\Python{versionPostfix}\python{versionPostfix}.dll");
RuntimeData.FormatterType = typeof(NoopFormatter);
try
{
PythonEngine.Initialize();
using (var gil = Py.GIL())
{
dynamic np = Py.Import("numpy");
Console.WriteLine(np.cos(np.pi * 2));
dynamic sin = np.sin;
Console.WriteLine(sin(5));
double c = (double)(np.cos(5) + sin(5));
Console.WriteLine(c);
dynamic a = np.array(new List<float> { 1, 2, 3 });
Console.WriteLine(a.dtype);
dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
Console.WriteLine(b.dtype);
Console.WriteLine(a * b);
}
}
finally
{
PythonEngine.Shutdown();
}