方法一:Python.Runtime调用
用Python.Runtime调用可以调用到python的函数,直接在vs2019的【管理NuGet程序包】下载Python.Runtime.NETStanda和Python的运行环境。
public void pytest()
{
string CurrentPath = System.IO.Directory.GetCurrentDirectory();
string ScriptFileName = CurrentPath + "\\script\\detector4";//存放python脚本的目录
string pathToPython =
@"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64";//python的运行环境目录
string path = pathToPython + ";" +
Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", path, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", pathToPython, EnvironmentVariableTarget.Process);
var lib = new[]
{
ScriptFileName,
Path.Combine(pathToPython, "Lib"),
Path.Combine(pathToPython, "DLLs")
};
string paths = string.Join(";", lib);
Environment.SetEnvironmentVariable("PYTHONPATH", paths, EnvironmentVariableTarget.Process);
using (Py.GIL()) //Initialize the Python engine and acquire the interpreter lock
{
try
{
// import your script into the process
dynamic sampleModule = Py.Import("PixetDemo");//python脚本文件名
int x = 3;
int y = 4;
dynamic results = sampleModule.PixetInit(x,y);
Console.WriteLine("Results: " + results);
}
catch (PythonException error)
{
// Communicate errors with exceptions from within python script -
// this works very nice with pythonnet.
Console.WriteLine("Error occured: ", error.Message);
}
}
}
PixetDemo.py
# -*- coding:utf-8 -*-
import sys
import numpy as np
def PixetInit(x,y):
return(x+y)
方法二:cmd调用
public static void pythonDetector4(string[] strArr)
{
//脚本所在地址
string CurrentPath = System.IO.Directory.GetCurrentDirectory();
string ScriptFileName = CurrentPath + "\\script\\detector4\\PixetDemo.py";
string sArguments = ScriptFileName; //脚本执行文件
//用于执行程序最后的
string sep = "-u";
Process process = new Process();
try
{
process.StartInfo.FileName = @"python.exe";
//构建执行文件以及参数
foreach (string sigstr in strArr)
{
sArguments += " " + sigstr;
}
sArguments += " " + sep;
//传递给进程
process.StartInfo.Arguments = sArguments;
process.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
process.StartInfo.CreateNoWindow = true; //是否在新窗口中启动该进程的值 (不显示程序窗口)
process.StartInfo.RedirectStandardInput = true; // 接受来自调用程序的输入信息
process.StartInfo.RedirectStandardOutput = true; // 由调用程序获取输出信息
process.StartInfo.RedirectStandardError = true; //重定向标准错误输出
process.Start();// 启动程序
process.BeginOutputReadLine();
process.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceivedText);
process.WaitForExit(); //等待程序执行完退出进程
process.Close();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". 检查文件路径.");
}
else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
Console.WriteLine(e.Message + ". 你没有权限操作文件.");
}
}
}
private static void p_OutputDataReceivedText(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
resultDetector4 = e.Data;//接受cmd传来的数据
Tools.WriteLogs(null, resultDetector4);
}
}
用cmd调用不需要下载什么,只要python能运行即可。最近的一个项目要求传输数据的实时性,python这边会每隔一秒把数据写到控制台我需要马上没间隔的给读出来进行实时性的处理,可是这是个异步输出流,这个愁死我了。然后才想到能不能直接调用python的函数,开始想用IronPython,但是python环境需要numpy怎么也装不上。最后才用到Python.Runtime调用的。