c#利用ironpython调用python

  • python用ironpython,只支持python2

具体下载安装步骤参考链接:

https://www.cnblogs.com/nickli/archive/2011/02/27/1966144.html

ps:记得下载2.7的版本

 

  • 调用外部命令,适用于python2和python3

System.Diagnostics.Process.Start(fileName);

 

  • 测试代码如下:

c#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//下载2.7版本,注意添加引用对用的.net框架版本
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.IO;//读写文件用到

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                Console.Write("python2 test\r\n");
                //1.IronPython只适用于python2.7
                //创建一个Python的运行环境
                ScriptRuntime pyRuntime = Python.CreateRuntime();
                //使用.net4.0的语法创建了一个动态的对象
                dynamic obj = pyRuntime.UseFile("test.py");//和exe程序放在同一路径下
                //获取python程序中的返回值
                string strPy = obj.test("tom");
                Console.Write(strPy + "\r\n");

                Console.Write("python3 test\r\n");
                //2.调用外部的命令,启动bat脚本,适用于python3
                //通过将数据保存在data.txt中实现python和C#之间值传输
                //场景一:python脚本写数据,c#读数据
                //string fileName = "test.py";
                //System.Diagnostics.Process.Start(fileName);
                string fileName = System.IO.Directory.GetCurrentDirectory() +         
                                  "\\runPy.bat";
                System.Diagnostics.Process.Start(fileName);
                string path = "F:\\data.txt";
                Read(path);

                //场景二:c#写数据,python读数据,再返回给c#
                //Write(path);
                //string s = obj.read();
                //Console.Write(s);
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                Console.Write(err);
            }
        }


        //读txt文件
        static void Read(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.Default);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line.ToString() + "\r\n");
            }
sr.Close();
        }

        //写txt文件
        static void Write(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write("hi\r\nfriend!\r\n");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

    }
}

经测试c#调用python3脚本比较有效的方式是调用bat脚本的方式,bat内容如下:

runPy.bat

python test.py

python代码test.py

# 待c#调用的函数,获取C#输入的参数,返回给C#一个字符串
def test(name):
    s = 'hello ' + name + '(this sentence from python)'
    #print(s)
    return s

#写txt文件  
def write():
    #import os
    #print("os.getcwd()=%s" % os.getcwd())
    with open('F:\data.txt','w') as f:
        f.write('hello world!!!')
        #print('test')
    f.close()

#读txt文件
def read():
    f = open('F:\data.txt')
    #print(f.read())
    return (f.read())

write()
#read()

如下结果所示:

python 2 test是利用ironpython实现c#和python的调用与交互 

Python 3 test是调用外部命令启动python脚本,python写,c#读

Python3 test中也可先c#写,python读,再通过ironpython将值给C#,如下图所示

 

猜你喜欢

转载自blog.csdn.net/feiyang5260/article/details/84887103
今日推荐