vs2015 C#调用python脚本包含第三方库

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

namespace python_test
{
    public partial class Form1 : Form
    {
        public static Form1 mainFrm;

        public Form1()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            mainFrm = this;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] strArr = new string[2];//参数列表
            string sArguments = @"number_detection.py";//这里是python的文件名字
            RunPythonScript(sArguments, "-u", strArr);
            
        }

        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文件夹中可以这样操作)
            p.StartInfo.FileName = @"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的结果
            Form1.mainFrm.textBox1.Text = text;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }
    }
}

本来想用C++但是第三方库支持的不好,跑不通就换成C#了正好做界面,也不错。

其中开头的这个public static Form1 mainFrm;以及System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;走是为了在静态函数中使用控件加的,这个方法可以获取python脚本最后输出的print的结果,不过我这里面还有图片还得试试别的方法。。。

猜你喜欢

转载自blog.csdn.net/wi162yyxq/article/details/91417137