使用C#调用Pyhon复杂程序

今天想使用python程序生成数据可视化的部分图形数据,首先搜索到了以下两个帖子,并尝试按其方法调用:

https://www.cnblogs.com/zoe-yan/p/10374757.html

上述方法使用了.net的IronPyhon来调用外部pyhon程序,调用简单的python包时,是可以正常使用的。

但是,当我尝试引入以下两个包进行数据分析时,发现根本不行:

import matplotlib.pyplot as plt

import pandas as pd

要么报named matplotlib.pyplot  is not module,要么就是奇怪的Invalid sytax,或者其它的什么错误,所以,调用类似机器学习与图像处理相关的复杂包时不可行!

后来读到一篇文章,原来在pyhon3.0以后,机器学习中常用的matplotlib、pandas 都非常复杂,而.net的IronPyhon没有得到及时更新,基本上是不能处理这些包的,果断放弃使用IronPyhon,转而使用弹出黑屏的cmd方法调用。这个方法果然奏效,不过在解决读取返回值时以及让cmd窗口自动关闭时,使用了一点技巧,故在此进行记录:

C#程序:

static void Main(string[] args)
        {
            Process p = new Process();
            string path = "python D:\\SVN\\004SheildOnLine\\003Source\\IronPython\\test2.py";
            string sArguments = path;

            //传递python参数
            //ArrayList arrayList = new ArrayList();
            //arrayList.Add("1");
            //arrayList.Add(2);
            //arrayList.Add("3");
            //foreach (var param in arrayList)//添加参数
            //{
            //    sArguments += " " + param;
            //}

            //实用cmd执行程序
            p.StartInfo.FileName = "cmd.exe"; //cmd命令行
            //p.StartInfo.Arguments = sArguments;//启动并执行python
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            //启动进程
            p.Start();

            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
            p.StandardInput.WriteLine(sArguments + "&exit");
            p.StandardInput.AutoFlush = true;
            string result = p.StandardOutput.ReadToEnd();
            string[] array = result.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            if (array.Length > 1)
                result = array[array.Length-2];
            //只取最后一行
            p.WaitForExit();
            p.Close();

            Console.WriteLine(result);
            Console.ReadLine();
        }

pyhon程序:

import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.family'] = ['simHei']
plt.rcParams['axes.unicode_minus']=False
def Test():
    tbm706=pd.read_csv("D:/sklearn/projects/data/706.csv",thousands=',')
    tbm706["总推进力"].hist(bins=50,figsize=(20,15),color='blue')
    plt.savefig(fname="tag1.png",figsize=[300,60])
    #plt.show()
    strOK="First Test"
    print(strOK)
    return strOK

Test()


 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#调用Python程序可以通过以下步骤实现: 1. 首先,将Python程序转换为动态链接库(dll)。这可以通过使用Cython或者使用Python的ctypes库来实现。在转换为dll之前,确保已经安装了Python运行环境,并且安装了所需的第三方库(如numpy)\[1\]。 2. 在C#中,使用DllImport特性来导入Python的dll文件。这样可以在C#调用Python的函数。确保在C#项目中引用了Python的dll文件。 3. 在C#调用Python函数时,需要传递参数并接收返回值。可以使用C#的InteropServices命名空间中的Marshal类来处理参数和返回值的转换。 下面是一个示例代码,演示了如何在C#调用Python程序: ```csharp using System; using System.Runtime.InteropServices; public class Program { \[DllImport("python_dll_path", CallingConvention = CallingConvention.Cdecl)\] public static extern double func(string a, string b); public static void Main(string\[\] args) { string a = "2"; string b = "3"; double result = func(a, b); Console.WriteLine(result); } } ``` 在上面的代码中,`python_dll_path`是Python程序转换为的dll文件的路径。`func`是Python程序中的函数名,通过DllImport特性导入。 请注意,这只是一个简单的示例,实际情况可能会更复杂。在实际使用中,还需要处理异常、错误检查等情况。 希望这个回答对您有帮助!\[1\] #### 引用[.reference_title] - *1* [c#调用python的四种方法(尝试了四种,只详细讲解本人成功的后两种,其余方法只列出,详细用法请自行谷歌...](https://blog.csdn.net/qq_42063091/article/details/82418630)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [c#调用python的三种方法](https://blog.csdn.net/qq_36744449/article/details/116134794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值