今天想使用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()