C#中使用python(基于Process-C#自带库)

C#中使用python(基于Process-C#自带库)

启动一个外部程序所使用的类是Process

ProcessStartInfo类只是用来传入Process类所需要的参数,可以通过直接给Process对象的属性赋值而达到相同的效果。

可以从 Python 的 os 的 标准输出 (sys.stdout.write) 中返回给 cshap

csharp 执行 命令行 的方法 // 可以获取到 py 脚本 print 的值
一般使用 json 作为数据结构的格式传递给 Python, 但是命令不能正常传递 json 字符串 给 Python 获取, 所以得用曲线救国的方式 base64 encode 一下给 py, 然后在 py 在 decode 解出正常的 json

csharp public static string Base64Encode(string plainText) {

var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);

return System.Convert.ToBase64String(plainTextBytes);

}

public static string Base64Decode(string base64EncodedData) {

var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);

return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

}

python def base64Encode(plainText: str) -> str:

return base64.encodebytes(plainText.encode()).decode()

def base64Decode(encodedData: str) -> str:

return base64.decodebytes(encodedData.encode()).decode()

//调用Python程序
Process p = new Process();//开启一个新进程
string filePath = @"C:\test.py";//参数由目标应用程序进行分析和解释,因此必须与该应用程序的预期保持一致。
p.StartInfo.FileName = @"C:\Python\Python36\python.exe";//要启动的应用程序的名称
p.StartInfo.Arguments = filePath;
p.StartInfo.UseShellExecute = false;//不使用shell
p.StartInfo.CreateNoWindow = true;//为true,则启动该进程而不新建窗口
p.Start();//开始进程

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

namespace CSharp调用python
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Process p = new Process();
            string path = "-u test.py";//待处理python文件的路径,本例中放在debug文件夹下
            string sArguments = path;
            ArrayList arrayList = new ArrayList();
            arrayList.Add("1");
            arrayList.Add("2");
            foreach (var param in arrayList)//添加参数
            {
                sArguments += " " + param;
            }

            p.StartInfo.FileName = @"E:\software\Anaconda3\python.exe"; //python的安装路径
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.EnableRaisingEvents = true;// 启用Exited事件  
            //p.Exited += new EventHandler(CmdProcess_Exited);
            p.Start();//启动进程
            p.BeginOutputReadLine();
            //p.WaitForExit();
            p.Close();
            Console.WriteLine("执行完毕!");
        }
        public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            string line;
            try
            {
                if (outLine.Data != null)
                {
                    line = (outLine.Data.ToString());
                    //在外部函数给Form赋值必须这样
                    Invoke(new Action(() =>
                    {
                        labelResult.Text += line;
                        labelResult.Text += "\r\n";

                    }));
                    Console.WriteLine(line);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

    }
}


版权声明:本文为qq_41375318原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。