C#调用命令行执行python脚本,这个办法可以调用python第三方模块和对本地文件进行操作
同步调用:
string pythonScriptPath = Server.MapPath(@"~\pythonScript");//python脚本所在的目录
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";//执行python.exe
//执行python脚本的命令
start.Arguments = pythonScriptPath + @"\sen2senScore_v3_console.py ";
//设置运行python脚本的初始目录 这里注意:如果你的python脚本有文件操作,必须设置初始目录
start.WorkingDirectory = pythonScriptPath;
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string line = reader.ReadLine();//每次读取一行命令行打印的信息
}
}
异步调用:
string pythonScriptPath = Server.MapPath(@"~\pythonScript");//python脚本所在的目录
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";//执行python.exe
//执行python脚本的命令
start.Arguments = pythonScriptPath + @"\sen2senScore_v3_console.py ";
//设置运行python脚本的初始目录 这里注意:如果你的python脚本有文件操作,必须设置初始目录
start.WorkingDirectory = pythonScriptPath;
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
// 异步获取命令行内容
process.BeginOutputReadLine();
// 为异步获取订阅事件
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
v.message = e.Data;//e.Data 就是命令行打印的最后一行信息
});
}
转载自:https://blog.csdn.net/sundaoli_0/article/details/83989185