• 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()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    //调用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();//开始进程
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    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);
                }
    
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
  • 相关阅读:
    CSS3入门
    Apache Doris的Bucket Shuffle Join实现
    MySQL索引、使用场景、失效场景、回表、索引覆盖
    计算机毕业设计ssm儿童成长记录与分享系统cc35g系统+程序+源码+lw+远程部署
    软件项目总结
    Vue技术-mapstart与mapGetters=》模块化+命名空间
    25.cuBLAS开发指南中文版--cuBLAS中的Level-2函数symv()
    win11识别不到外置机械硬盘
    费时3个月,靠着这篇软件测试进阶笔记,成功拿下了阿里、腾讯等10家offer
    Web项目如何做单元测试
  • 原文地址:https://blog.csdn.net/qq_41375318/article/details/127672732