zoukankan      html  css  js  c++  java
  • C# 调用 python3

    1.C# 调用python

    本质上是使用命令行运行python

    1.1 C# 使用命令行

    program.cs

    using System;
    using System.Diagnostics;
    using System.IO;
    
    namespace test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Program p = new Program();
                string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
                Console.WriteLine(result);
    
                Console.ReadKey();
            }
    
            public string run_cmd(string program, string cmd)
            {
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = program;
                start.Arguments = cmd;
                start.UseShellExecute = false;          // Do not use OS shell
                start.CreateNoWindow = true;            // We don't need new window
                start.RedirectStandardOutput = true;    // Any output, generated by application will be redirected back
                start.RedirectStandardError = true;     // Any error in standard output will be redirected back (for example exceptions)
                using (Process process = Process.Start(start))
                {
                    using (StreamReader reader = process.StandardOutput)
                    {
                        string result = process.StandardError.ReadToEnd();
                        if (result == null || result == "")
                        {
                            result = reader.ReadToEnd();
                        }
                        return result;
                    }
                }
            }
        }
    }

    代码运行结果
    代码运行结果

    • 调用run_cmd相当于执行了cmd命令,所以就有了使用命令行运行python脚本的方式

    1.2. C# 调用 python3脚本

    假设C盘根目录下有如下脚本 test1.py

    import sys
    
    def add(a,b):
        return a+b
    
    if __name__ == "__main__":
        print(sys.argv[1])
        print("hello python")

    program.cs 中加入函数runPython,并修改main函数

    static void Main(string[] args)
    {
        Program p = new Program();
        //string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
        string result = p.runPython("C:\test1.py", ""Form C#:"");
        Console.WriteLine(result);
    
        Console.ReadKey();
    }
    
    
    public string runPython(string filename, string cmd)
    {
        string cmd1 = string.Format("{0} {1}", filename, cmd);
        return run_cmd("python.exe", cmd1);
    }

    代码运行结果
    代码运行结果

    1.3 C# 调用python3内的函数

    我们知道使用python -c可以直接执行python代码,所以合理构造语句就可以直接调用python脚本内的函数了:python -c "print('hello python')"
    若要调用脚本里的函数,常规写法为:

    import sys
    sys.path.append('c:\')
    import test1
    print(test1.add(3,4))

    缩成一行就是python -c "import sys;sys.path.append('c:\');import test1;print(test1.add(3,4))"

    program.cs 中加入函数runPyFunc,并修改main函数

            static void Main(string[] args)
            {
                Program p = new Program();
                //string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
                //string result = p.runPython("C:\test.py", ""Form C#:"");
                string result = p.runPyFunc(@"C:\","test1","add","3,4");
                Console.WriteLine(result);
    
                Console.ReadKey();
            }
    
            public string runPyFunc(string path, string filename, string functionname, string parameter)
            {
                string cmd = string.Format("-c "import sys;sys.path.append('{0}');import {1};print({1}.{2}({3}))"", path, filename, functionname, parameter);
                return run_cmd("python.exe", cmd);
            }

    运行就可以得到结果“7”了

  • 相关阅读:
    User Get 'Access Denied' with Excel Service WebPart
    How To Search and Restore files from Site Collection Recycle Bin
    How To Collect ULS Log from SharePoint Farm
    How To Restart timer service on all servers in farm
    How to Operate SharePoint User Alerts with PowerShell
    How to get Timer Job History
    Synchronization Service Manager
    SharePoint 2007 Full Text Searching PowerShell and CS file content with SharePoint Search
    0x80040E14 Caused by Max Url Length bug
    SharePoint 2007 User Re-created in AD with new SID issue on MySite
  • 原文地址:https://www.cnblogs.com/lantingg/p/9418307.html
Copyright © 2011-2022 走看看