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

4次阅读

共计 2658 个字符,预计需要花费 7 分钟才能阅读完成。

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 框架了。

正文完
 0