C# 调用 Python 3 脚本

/ 0评 / 1

啊,又不复习搞这个干嘛!。。。
emmmm好吧直接正文

方法一:使用命令行方式执行

优点:支持Python3和其他脚本如php等
缺点:如果需要发送请求等需要等待的操作不能在程序中查看状态(程序仍在执行,这个问题不知道能不能解决,日后再说)

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace PythonDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string code = richTextBox1.Text;

            //var file = File.CreateText("test.py");
            //file.Write(code.ToString());
            //file.Close(); //输出到临时文件,方便python执行
            Thread thread = new Thread(Start);
            thread.IsBackground = true;
            thread.Start();

        }

        public void Start()
        {
            Process p = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"python", //这样来调用python,需要将python加入Path环境变量内或者直接输入python文件的绝对路径
                    Arguments = "test.py",
                    UseShellExecute = false,    //是否使用操作系统shell启动
                    RedirectStandardInput = true, //接受来自调用程序的输入信息
                    RedirectStandardOutput = true, //由调用程序获取输出信息
                    RedirectStandardError = true, //重定向标准错误输出
                    CreateNoWindow = true, //不显示程序窗口
                }
            };
    
            p.Start();//启动程序
            p.OutputDataReceived += OutputDataReceived;//异步

            //获取输出信息
            //string output = p.StandardOutput.ReadToEnd();

            p.BeginOutputReadLine();
            p.WaitForExit();                            //等待程序执行完退出进程  
            p.Close();

        }

        private void OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            //this.BeginInvoke(new Action(() => {  }));
            richTextBox1.Text += e.Data + "\r\n";
        }
    }
}

方法二:使用IronPython

先来看看IronPython的介绍:
IronPython是一个.NET平台上的Python实现,包括了完整的编译器、执行引擎与运行时支持,能够与.NET已有的库无缝整合到一起。
IronPython已经很好的集成到了.NET framework中,所以Ironpython和C#的交互也就变得很简单了。下面就通过一些简单的例子来看看IronPython和C#之间的交互。
1.先在项目中添加NuGet引用:IronPython.dll,Microsoft.Scripting.dll
2.调用前添加两个引用再调用

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

3.要调用的地方如下:

ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic python = pyRuntime.UseFile("test.py");
string a = python.text();
textBox1.AppendText(a);

调用复杂含三方类库的python文件

安装Python2.7
注意在Python2.7安装目录;

import sys
sys.path.append(r'C:\Python27')
sys.path.append(r'C:\Python27\Lib\DLLs')
sys.path.append(r"C:\Python27\Lib")
sys.path.append(r"C:\Python27\Lib\site-packages")
sys.path.append(r'C:\Python27\Lib\site-packages\requests-2.8.1-py2.7.egg')
import requests

优点:兼容性高
缺点:只支持Python2.x

以后有空再研究,(闪

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注