Python.Net - 如何从文件(.Py)运行 Python 脚本

4
如何使用Python.Net库运行.py文件并调用函数。 我尝试了下面的代码,但它没有运行。
    using (Py.GIL()){
      var fromFile = PythonEngine.Compile(null, @"C:\PycharmProjects\pythonenet\main.py", RunFlagType.File);
      fromFile.InvokeMethod("replace");//
    }

主程序文件 main.py:

import re
def replace():
 print(re.sub(r"\s","*","Python is a programming langauge"))

当我尝试从字符串中运行时,它可以正常工作。

       using (Py.GIL()){
          string co = @"def someMethod():
                print('This is from static script')";
          var fromString = PythonEngine.ModuleFromString("someName", co);
          fromString.InvokeMethod("someMethod");   
        }
1个回答

5

最终,我采用了以下解决方案。

using (Py.GIL()){
    dynamic os = Py.Import("os");
    dynamic sys = Py.Import("sys");
    sys.path.append(os.path.dirname(os.path.expanduser(filePath)));
    var fromFile = Py.Import(Path.GetFileNameWithoutExtension(filePath));
    fromFile.InvokeMethod("replace");
}

3
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接