简体   繁体   English

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

[英]Python.Net - How to run python script from file(.Py)

How to run.py files and call function by using python.Net library.如何使用python.Net库运行.py文件并调用function。 i have tried below code but it is not running.我试过下面的代码,但它没有运行。

    using (Py.GIL()){
      var fromFile = PythonEngine.Compile(null, @"C:\PycharmProjects\pythonenet\main.py", RunFlagType.File);
      fromFile.InvokeMethod("replace");//
    }

main.py file:主.py文件:

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

When i try to run from string it is working.当我尝试从字符串运行时它正在工作。

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

The purpose of Python.NET (pythonnet) is to enable fast scripting for .NET developers. Python.NET (pythonnet) 的目的是为 .NET 开发人员启用快速脚本。 Python.NET is used to script .NET components (like C#, VB.NET, F3). Python.NET 用于编写 .NET 组件(如 C#、VB.NET、F3)脚本。 If your goal is to make one Python program run another Python program, you can use the features provided by Python:如果您的目标是让一个 Python 程序运行另一个 Python 程序,您可以使用 Python 提供的功能:

# service.py
import main

def something():
    print('service: something()')

if __name__ == '__main__':
   something()
   main.something()
# main.py
import subprocess

def something():
    print('main: something()')

if __name__ == '__main__':
    something()
    subprocess.call("service.py", shell=True)

The output in the first group below is produced by running the main.py program, and the output in the second group is produced by running the service.py program.下面第一组的output是运行main.py程序产生的,第二组的output是运行service.py程序产生的。

# Running the "main.py" file produces the following output:
main: something()
service: something()
main: something()

# Running the "service.py" file produces the following output:
service: something()
main: something()

Note that two different solutions are used above:请注意,上面使用了两种不同的解决方案:

  1. Added import main command line to include main.py file in service.py file.添加了import main命令行以在service.py文件中包含main.py文件。
  2. The subprocess module was used to run the service.py file from the main.py file. subprocess模块用于从main.py文件运行service.py文件。

Finally i ended up with the following solution.最后我得到了以下解决方案。

              using (Py.GIL()){
                    string file_path = @"C:\PycharmProjects\pythonnet\main.py";
                    string final_path = null;
                    string module_name = null;
                    if (file_path.EndsWith(".py"))
                    {
                        int delim = file_path.LastIndexOf(@"\");
                        final_path = file_path.Substring(0,delim > 0 ? delim : 0); //C:\PycharmProjects\pythonnet
                        int module_length = (file_path.Length - delim) - 4;
                        if (module_length > 0)
                            module_name = file_path.Substring(delim+1, module_length);//main
                    }
                    if (final_path != null && module_name != null)
                    {
                        dynamic ps = Py.Import("sys");
                        ps.path.append(final_path);
                        var obj = Py.Import(module_name);
                        Console.WriteLine(obj.InvokeMethod("replace"));
                    }else
                       throw new Exception("Invalid filename or file path");
          }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM