关于python:C调用Python方式之一

Python是AI畛域的最支流的编程语言,没有之一。而利用开发畛域则通常不会选用Python语言。如果遇到利用开发过程中波及AI算法,那就必然要面对跨语言通信的问题。明天来介绍下C#中执行Python脚本的形式之一,当然还有其余形式也能实现。
须要装置python安装包和库环境,利用c#命令行,调用.py文件执行

  这种办法:通过C#命令行调用.py文件 == 通过python.exe 关上.py文件

  他的适用性强,你只有保障你的.py程序可能通过python.exe关上,应用就不会有大问题,同时还有一些须要留神的点。

  (1)文件门路不能应用相对路径(例:path = ./文件名 或者path = 文件名 ),会报错,这一块我不分明是否他人没遇到,反正我的话是始终会报这种谬误。

  解决办法也很简略,要么用绝对路径,要么导入os库,通过os.path.dirname(__file__)能够失去以后文件的门路,即path = os.path.dirname(__file__) + ‘\文件名’

  (2)门路距离须要用/代替\;同时“\”作为输出参数偶然也会有出现异常的状况,起因不明。集体倡议将输出门路参数全副提前替换

  (3)不能调用py文件的接口,函数办法

  (4)最好在程序前附加异样检测解决(try,exception),便于获取异样(C#调用Python偶然库,或者一些门路会有异样,导致间接运行失败)
筹备一个简略的Winform程序和Python脚本。Winform程序如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CsharpCallPython
{
    public partial class Form1 : Form
    {
        private Process progressTest;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //string path = Application.StartupPath + @"\CsharpCallPython.py";//py文件门路";
                string path= "F:\\study\\mycode\\python\\PythonTest\\flaskdemo\\mypthondemo.py";
                int a = Convert.ToInt32(txtA.Text);
                int b = Convert.ToInt32(txtB.Text);
                StartTest(path, a, b);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        public void outputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                this.Invoke(new Action(() => {
                    this.txtResult.Text = e.Data;
                }));
            }
        }

        public bool StartTest(string pathAlg, int a, int b)
        {
            bool state = true;

            if (!File.Exists(pathAlg))
            {
                throw new Exception("The file was not found.");
                return false;
            }
            string sArguments = pathAlg;
            sArguments += " " + a.ToString() + " " + b.ToString() + " -u";//Python文件的门路用“/”划分比拟常见

            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"D:\Python36\python.exe";//环境门路须要配置好Python的理论装置门路
            start.Arguments = sArguments;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardInput = true;
            start.RedirectStandardError = true;
            start.CreateNoWindow = true;

            using (progressTest = Process.Start(start))
            {
                // 异步获取命令行内容
                progressTest.BeginOutputReadLine();
                // 为异步获取订阅事件
                progressTest.OutputDataReceived += new DataReceivedEventHandler(outputDataReceived);
            }
            return state;
        }

    }
}

Python脚本如下:

# -*- coding: utf-8 -*-
"""
File Name:   PythonTest
Author:      Michael
date:        2022/10/27
"""

import numpy
import os
import sys


def Add(a,b):
    return a+b


if __name__=='__main__':
    try:
        # 代码行
        a = int(sys.argv[1])
        b = int(sys.argv[2])
        c = Add(a,b)
    except Exception as err:
        # 捕获异样
        str1 = 'default:' + str(err)
    else:
        # 代码运行失常
        str1 = c
    print(str1)

从以上代码不难看出,这是个实现简略的加法运算的性能。为了重大在C#执行Python脚本的可行性,才写了个Python脚本来实现两个数的求和运算。
运行Winform程序,很快得出后果了:

【论断】:
通过这种形式,是能够实现Python脚本的最终运行。但这并不是跨语言通信的个别解决形式。因而还是有必要好好钻研下RPC框架了。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理