參考文章:c#調用python腳本
最近項目中遇到使用C#調用Python的項目,其中涉及batchcompute庫。遇到一些問題,記錄一下。
- 項目使用的是IronPython 2.7.9版本包,需要在Nuget安裝IronPython,
- 如果報錯,需要更新Nuget版本則下載對應版本即可:https://dist.nuget.org/index.html
添加引用:IronPython.dll,Microsoft.Scripting.dll(在IronPython的安裝目錄中)
一、C#調用簡單python文件
文件名未hello.py的python文件內部代碼:
#文件目錄 /Module/python/hello.py
import time
def welcome(name):
return "hello " + name
def Add(a, b):
return a + b
C#文件相關代碼:
…
if (true)
{
Microsoft.Scripting.Hosting.ScriptRuntime pyRunTime = IronPython.Hosting.Python.CreateRuntime();
dynamic obj = pyRunTime.UseFile("Module/python/hello.py");
Console.WriteLine(obj.welcome("寶寶"));
Console.WriteLine(obj.Add(5, 7)); //方法名必須大小寫區分正確
Console.ReadKey();
}
…
執行結果爲:
二、C#調用含第三方庫python文件(未解決)
文件名未hello.py的python文件內部代碼修改爲:
import time
import batchcompute
from batchcompute import CN_ZHANGJIAKOU as REGION
from batchcompute import Client, ClientError
def welcome(name):
return "hello " + name
def Add(a, b):
return a + b
C#文件相關代碼:
if (true)
{
var options = new Dictionary<string, object>();
options["Frames"] = true;
options["FullFrames"] = true;
var engine = IronPython.Hosting.Python.CreateEngine(options);
var scope = engine.CreateScope();
var paths = engine.GetSearchPaths();
paths.Add(@"C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Lib\site-packages\batchcompute-2.1.4-py3.8.egg");
paths.Add(@"C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Lib\site-packages");
paths.Add(@"C:\Users\Administrator\AppData\Local\Programs\Python\Python38\Lib");
paths.Add(@"C:\Users\Administrator\AppData\Local\Programs\Python\Python38");
engine.SetSearchPaths(paths);
var source = engine.CreateScriptSourceFromFile("Module/python/hello.py"); //ListClusterInstances.py
source.Execute(scope);
var welcome = scope.GetVariable<Func<string, string>>("welcome");
var result1 = welcome("寶寶");
Console.WriteLine(result1);
var Add = scope.GetVariable<Func<int, int, int>>("Add");
var result2 = Add(5, 7).ToString();
Console.WriteLine(result2);
}
執行結果報出的錯誤始終是不知緣由,結果如下:
還望各路路過的大神能不吝賜教,指點一二,解除小白心中的疑惑