c#语言调用python编写的应用程序
windows
windows平台下,python打包后的应用程序为.exe程序
using (Process myProcess = new Process())
{
myProcess.StartInfo.UseShellExecute = false;
var guid = System.Guid.NewGuid().ToString();
var jsonfile = guid + ".json";
string jsonPath = ProjectPath + @"python\dist\json\" + jsonfile;
File.WriteAllText(jsonPath, jsonData);
myProcess.StartInfo.FileName = ProjectPath + @"python\dist\python\python.exe";
myProcess.StartInfo.Arguments = jsonfile + " " + resultTemlate + " "+flag + " "+Name;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.ErrorDialog = false;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.Start();
myProcess.WaitForExit();
dicresult["msg"] = myProcess.ExitCode;
dicresult["code"] = 1;
dicresult["json"] = jsonPath;
dicresult["url"] = "DownloadExport\\python\\" + Name;
}
liunx
windows平台下,python打包后的应用程序为文件名程序
using (Process myProcess = new Process())
{
// 默认为4,代表导出excel的周月报
var flag = 4;
//excel文件的名字
string Name = Guid.NewGuid().ToString(); //OurReport.Name;
//json文件,将传入python.exe的数据写入json文件中,并保存在python\dist\json\下
var jsonpath = string.Format(@"{0}json/{1}.json", distPath, Name); //OurReport.Name + ".json";
Logger.Debug("jsonpath:" + jsonpath);
var jsonfile = string.Format(@"{0}.json", Name); //OurReport.Name + ".json";
File.WriteAllText(jsonpath, OurReport.ContentExcel);
var resultFilePath1 = string.Format(@"{0}export/", distPath, Name);
string path = string.Format(@"{0}json/{1}.json", distPath, Name);
Logger.Debug("json文件:" + path);
string exe = string.Format("{0}python", distPath);
Logger.Debug("应用程序位置:" + exe);
//插件位置,在python\dist\python\python
myProcess.StartInfo.FileName = "sh";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.ErrorDialog = false;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.Start();
string minlin="./python"+" " + jsonfile + " " + resultFilePath1 + " " + flag + " " + OurReport.Name + " " + path;
myProcess.StandardInput.WriteLine("cd /usr/songguoyunku/netcoreapp3.1/App_Data/python/dist/python");
myProcess.StandardInput.WriteLine(minlin);
myProcess.StandardInput.WriteLine("exit");
string strResult = myProcess.StandardOutput.ReadToEnd();
Logger.Debug("执行程序输出:" + strResult);
myProcess.WaitForExit();
var result = myProcess.ExitCode;
Logger.Debug("Python 执行调用返回编码 Code 为: " + result);
// 读取最终生成的文件
var resultFilePath = string.Format(@"{0}export/{1}.xlsx", distPath, Name);
byte[] fileBytes = File.ReadAllBytes(resultFilePath);
File.Delete(resultFilePath); // 删除临时文件
return fileBytes;
}
}