C#调用Python的两种方法

方法一: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调用的。

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#调用Python有多种方法可以实现。其中一种方法是使用IronPython。首先,你需要安装IronPython,你可以从http://ironpython.codeplex.com/下载并安装IronPython,或者只下载"Binaries"版本并将IronPython.dll、Microsoft.Scripting.dll和Microsoft.Dynamic.dll拷贝到目标目录。接下来,你需要创建一个C#的控制台应用程序,并添加对IronPython.dll和Microsoft.Scripting.dll的引用。然后,将Python文件添加到项目中,并设置"复制到输出目录"为始终复制,以避免运行时找不到文件。在C#调用Python脚本文件时,你需要引用IronPython.Hosting和Microsoft.Scripting.Hosting命名空间,并使用以下代码进行调用: ``` ScriptRuntime pyRuntime = Python.CreateRuntime(); dynamic pyobj = pyRuntime.UseFile("hello.py"); Console.WriteLine(pyobj.welcome("Nick")); ``` 如果需要传递复杂参数,比如数组或对象,你可以直接在C#中传递给Python。例如: ``` ScriptRuntime pyRuntime = Python.CreateRuntime(); dynamic pyobj = pyRuntime.UseFile("hello.py"); double\[\] x = { 1, 2, 3 }; Console.WriteLine(pyobj.welcome(x)); ``` 在Python脚本中,你可以通过索引访问传递的数组,并进行相应的操作。例如: ``` def welcome(x): return "the 2th value of x is: " + '%f' % x\[1\] ``` 这样,你就可以在C#调用Python脚本并传递参数了。请注意,以上只是使用IronPython的一种方法,还有其他几种方法可以实现C#调用Python。你可以参考https://blog.csdn.net/qq_42063091/article/details/82418630了解更多详细信息。 #### 引用[.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^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [C#调用Python脚本步骤](https://blog.csdn.net/hustlei/article/details/86688342)[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^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值