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的結果,不過我這裏面還有圖片還得試試別的方法。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章