如何在C#中运行一个外部Python脚本,该脚本自己导入3rd party库?

时间:2018-11-20 15:53:35

标签: c# python visual-studio speech-recognition ironpython

我试图将Python代码与C#结合起来,以在我的C#应用​​程序中使用所有很酷的库,例如语音识别。

我为python(IronPython)创建了两个不同的项目,其中通过VS2017中的python环境包含了我需要的模块(Speech Recognition),另一个是我要调用的控制台应用程序这个程序。

我认为关键是要更改Ironpython的searchPaths,然后它才能工作。

也许我做错了什么,或者它根本不应该工作?


C#代码Main.cs:

using IronPython.Hosting;
using System.Collections.Generic;
private static void Main(string[] args)
    {
        //Using Iron python
        var engine = IronPython.Hosting.Python.CreateEngine();
        System.Console.WriteLine("Search paths:");
        ICollection<string> searchPaths = engine.GetSearchPaths();
        foreach (string path in searchPaths)
        {
            System.Console.WriteLine(path);
        }
        System.Console.WriteLine();           
        searchPaths.Add("..\\..");
        ///Trying to add a searchPath for the place with the module I need
        searchPaths.Add(@"C:\Program Files (x86)\Microsoft Visual
        Studio\Shared\Anaconda3_64\Lib\site-packages");
        engine.SetSearchPaths(searchPaths);
        var res = engine.CreateScriptSourceFromFile(
        @"D:\Python\Projects\TestSpeechRecognition
        \TestForNETinPython\TestForNETinPython.py"
        );
        engine.ImportModule("speech_recognition");
        var result = res.Execute();
   }

Python代码

 import speech_recognition as sr
 r = sr.Recognizer()
 with sr.Microphone() as source: 
    print ("Hello: ")
    audio = r.listen(source)
 try:
   print ("I said: " + r.recognize_google(audio))
except sr.UnknownValueError:
   print ("Cant't rec")
except sr.RequestError as e:
   print ("Can't connect: (0)".format(e))

例外:

  

未处理的异常:   IronPython.Runtime.Exceptions.ImportException:没有名为Speech_recognition的模块      在IronPython.Hosting.PythonService.ImportModule(ScriptEngine引擎,字符串名称)      在IronPython.Hosting.Python.ImportModule(ScriptEngine引擎,字符串moduleName)      在D:\ Python \ Projects \ TestSpeechRecognition \ Test \ Program.cs:line 26中的Test.Program.Main(String [] args)

我什至读过一些有关创建诸如http://www.needfulsoftware.com/IronPython/IronPythonCS2之类的模块的文献,或者是针对pythonnet的,有点令人毛骨悚然,但是我想它可能有用(NoteBook)。
   希望有人可以用它来解决问题。

0 个答案:

没有答案
相关问题