C#调用python脚本

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#调用python脚本

人工智能之浪潮   2022-09-29 我要评论

C#调用python脚本

在平常工程项目开发过程中常常会涉及到机器学习、深度学习算法方面的开发任务,但是受限于程序设计语言本身的应用特点,该类智能算法的开发任务常常使用Python语言开发,所以在工程实践过程中常常会遇到多平台程序部署问题。本文总结了C#调用Python程序的各种方法,希望能够给各位读者提供一定的参考。

方式一

使用c#,nuget管理包上下载的ironPython安装包适用于python脚本中不包含第三方模块的情况

IronPython 是一种在 NET 和 Mono 上实现的 Python 语言,由 Jim Hugunin(同时也是 Jython 创造者)所创造。它的诞生是为了将更多的动态语音移植到NET Framework上。

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
 
namespace CSharpCallPython
{
    class Program
    {
        static void Main(string[] args)
        {
            ScriptEngine pyEngine = Python.CreateEngine();//创建Python解释器对象
            dynamic py = pyEngine.ExecuteFile(@"test.py");//读取脚本文件
            int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
            string reStr = py.main(array);//调用脚本文件中对应的函数
            Console.WriteLine(reStr);
 
            Console.ReadKey();
        }
    }
}
def main(arr):
    try:
        arr = set(arr)
        arr = sorted(arr)
        arr = arr[0:]
        return str(arr)
    except Exception as err:
        return str(err)

方式二

适用于python脚本中包含第三方模块的情况(与第四种类似)

using System;
using System.Collections;
using System.Diagnostics;
 
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Process p = new Process();
            string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下
            string sArguments = path;
            ArrayList arrayList = new ArrayList();
            arrayList.Add("com4");
            arrayList.Add(57600);
            arrayList.Add("password");
            foreach (var param in arrayList)//添加参数
            {
                sArguments += " " + sigstr;
            }
 
            p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();//启动进程
 
            Console.WriteLine("执行完毕!");
 
            Console.ReadKey();
        }
    }
}

Python代码

# -*- coding: UTF-8 -*-
import serial
import time
 
def resetIPC(com, baudrate, password, timeout=0.5):
    ser=serial.Serial(com, baudrate, timeout=timeout)
    flag=True
    try:
        ser.close()
        ser.open()
        ser.write("\n".encode("utf-8"))
        time.sleep(1)
        ser.write("root\n".encode("utf-8"))
        time.sleep(1)
        passwordStr="%s\n" % password
        ser.write(passwordStr.encode("utf-8"))
        time.sleep(1)
        ser.write("killall -9 xxx\n".encode("utf-8"))
        time.sleep(1)
        ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
        time.sleep(1)
        ser.write("reboot\n".encode("utf-8"))
        time.sleep(1)
    except Exception:
        flag=False
    finally:
        ser.close()
    return flag
 
resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

方式三

使用c++程序调用python文件,然后将其做成动态链接库(dll),在c#中调用此dll文件     

限制:实现方式很复杂,并且受python版本、(python/vs)32/64位影响,而且要求用户必须安装python运行环境

方式四

使用安装好的python环境,利用c#命令行,调用.py文件执行(推荐使用)

优点:执行速度只比在python本身环境中慢一点,步骤也相对简单

缺点:需要用户安装配置python环境

实用步骤:

1、下载安装python,并配置好环境变量等(本人用的Anaconda,链接此处不再提供)

2、编写python文件(这里为了便于理解,只传比较简单的两个参数)

#main.py
import numpy as np
import multi
import sys
 
def func(a,b):
    result=np.sqrt(multi.multiplication(int(a),int(b)))
    return result
 
 
if __name__ == '__main__':
    print(func(sys.argv[1],sys.argv[2]))
        3、在c#中调用上述主python文件:main.py
        private void Button_Click(object sender, RoutedEventArgs e)
        {
 
            string[] strArr=new string[2];//参数列表
            string sArguments = @"main.py";//这里是python的文件名字
            strArr[0] = "2";
            strArr[1] = "3";
            RunPythonScript(sArguments, "-u", strArr);
        }
        //调用python核心代码
        public static void RunPythonScript(string sArgName, string args = "", params string[] teps)
        {
            Process p = new Process();
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + sArgName;// 获得python文件的绝对路径(将文件放在c#的debug文件夹中可以这样操作)
            path = @"C:\Users\user\Desktop\test\"+sArgName;//(因为我没放debug下,所以直接写的绝对路径,替换掉上面的路径了)
            p.StartInfo.FileName = @"D:\Python\envs\python3\python.exe";//没有配环境变量的话,可以像我这样写python.exe的绝对路径。如果配了,直接写"python.exe"即可
            string sArguments = path;
            foreach (string sigstr in teps)
            {
                sArguments += " " + sigstr;//传递参数
            }
 
                sArguments += " " + args;
 
            p.StartInfo.Arguments = sArguments;
 
            p.StartInfo.UseShellExecute = false;
 
            p.StartInfo.RedirectStandardOutput = true;
 
            p.StartInfo.RedirectStandardInput = true;
 
            p.StartInfo.RedirectStandardError = true;
 
            p.StartInfo.CreateNoWindow = true;
 
            p.Start();
            p.BeginOutputReadLine();
            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            Console.ReadLine();
            p.WaitForExit();
        }
        //输出打印的信息
        static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                AppendText(e.Data + Environment.NewLine);
            }
        }
        public delegate void AppendTextCallback(string text);
        public static void AppendText(string text)
        {
            Console.WriteLine(text);     //此处在控制台输出.py文件print的结果
 
        }

方式五

c#调用python可执行exe文件,使用命令行进行传参取返回值

优点:无需安装python运行环境

缺点:

1、可能是因为要展开exe中包含的python环境,执行速度相当慢,慎用!

2、因为是命令行传参形式,故传参需要自行处理。ps:由于命令行传参形式为:xxx.exe 参数1 参数2 参数3....

使用步骤:

1、使用pyinstaller打包python程序;

2、在c#中调用此exe文件; 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们