[C# app] Pythonnet – .NET Core와 Python의 간단한 결합 :

Pythonnet – A Simple Union of .NET Core and Python You’ll Love

 

Pythonnet – .NET Core와 Python의 간단한 결합

나를 평가:
5.00/5 (10표)
2023년 1월 25일CPOL3분 읽기
C# 코드에서 Python을 호출하는 방법으로 "Python for .NET" 패키지 사용
Python과 C#은 매우 인기 있는 두 가지 언어입니다. 주로 C# 개발자로서 저는 Python과 인터페이스하고 싶은 상황이 있다는 것을 알게 되었습니다. 다음은 C# 코드에서 Python을 호출하는 방법으로 "Python for .NET" 패키지를 사용하는 예입니다.

Python은 점점 인기를 얻고 있는 강력하고 다재다능한 프로그래밍 언어입니다. 많은 사람들이 시작할 때 선택하는 첫 번째 프로그래밍 언어 중 하나입니다. 몇 년이 지난 후 내 블로그에서 가장 트래픽이 많은 게시물 중 일부는 C#과 Python을 함께 사용하는 방법을 살펴봅니다. 오늘, 우리는 C# .NET Core 애플리케이션 내에서 내 원래 기사 보다 훨씬 더 현대적인 접근 방식으로 Python을 사용하는 방법을 탐색할 것입니다 파이썬넷에 들어가세요!

Pythonnet 패키지 및 시작하기

우리는 이 목표를 달성하기 위해 Python for .NET을 살펴볼 것입니다 . 이 라이브러리를 사용하면 .NET Core 애플리케이션 내에서 실행 중인 컴퓨터에 설치된 Python을 활용할 수 있습니다. 사용하려는 해당 Python DLL을 가리키도록 구성해야 하며 몇 줄의 초기화 후에 경주를 시작합니다!

예제 1 – Pythonnet을 사용한 Hello World

시작하려면 NuGet 에서 pythonnet 패키지를 설치해야 합니다 완료하면 다음 코드를 사용하여 C# 코드에서 Python 스크립트를 실행할 수 있습니다.

씨#
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            using var scope = Py.CreateScope();
            scope.Exec("print('Hello World from Python!')");
        }
    }
}

이 코드는 런타임에서 Python DLL 경로를 설정하며 이는 필요한 단계입니다. 이것을 하는 것을 잊지 마세요 ! PythonEngine.Initialize()그런 다음 and 를 호출해야 합니다 Py.GIL(). 나중에 처리하고 싶으므로 명령문 을 고려하십시오 usingstatic Py사용할 범위를 생성하도록 클래스에 요청한 다음 일부 Python 코드를 실행하기 위해 Exec 메서드를 활용할 수 있습니다 . 이 예제에서는 Exec 메서드를 호출하여 Hello World from Python!콘솔에 " "를 인쇄하는 간단한 Python 스크립트를 실행합니다 .

예제 2 – Pythonnet 계산기!

Python C API를 사용하여 C# 코드에서 직접 Python 함수를 호출할 수도 있습니다. 이렇게 하려면 호출하려는 Python 함수에 대한 C# 래퍼를 만들어야 합니다. 다음은 두 개의 정수를 인수로 사용하고 그 합계를 반환하는 Python 함수에 대한 래퍼를 만드는 방법의 예입니다.

씨#
using System;
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            // NOTE: this doesn't validate input
            Console.WriteLine("Enter first integer:");
            var firstInt = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter second integer:");
            var secondInt = int.Parse(Console.ReadLine());

            using dynamic scope = Py.CreateScope();
            scope.Exec("def add(a, b): return a + b");
            var sum = scope.add(firstInt, secondInt);
            Console.WriteLine($"Sum: {sum}");
        }
    }
}

이 예에서는 Exec 메서드를 사용하여 add 두 개의 정수를 인수로 사용하고 해당 sum C#의 dynamic 키워드 덕분에 개체 에 직접 scope호출되는 메서드가 있다고 가정할 수 있습니다 .  마지막으로 C# 내부에 있는 것처럼 addC# 코드를 직접 사용하여 메서드를 호출합니다 . addC#에서 변수 에 할당된 반환 유형 sum 도 동적이지만 이 변수를 정수로 선언할 수 있으며 이 유형으로도 제대로 컴파일됩니다.

Pythonnet을 사용한 계산기 출력

간단한 Pythonnet 계산기의 콘솔 창 결과!

예제 3 – 개체 상호 운용성

Python 개체를 C# 함수에 전달할 수도 있고 그 반대의 경우도 가능합니다. 다음은 Python 목록을 C# 함수로 다시 수신하고 dynamic 키워드를 사용하지 않고 해당 요소를 반복하는 방법에 대한 예입니다.

씨#
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: Set this based on your Python install. 
        // This will resolve from your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            using var scope = Py.CreateScope();

            scope.Exec("number_list = [1, 2, 3, 4, 5]");
            var pythonListObj = scope.Eval("number_list");
            var csharpListObj = pythonListObj.As<int[]>();

            Console.WriteLine("The numbers from python are:");
            foreach (var value in csharpListObj)
            {
                Console.WriteLine(value);
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

이 예제에서는 Exec 메서드를 사용하여 Python 목록을 만들고 이라는 변수에 할당합니다 number_list그런 다음 Eval 메서드를 사용하여 개체 에 대한 참조를 가져온 list다음 As<T>정수 배열( 로 표시됨 int[])을 호출하여 결과를 변환할 수 있습니다. 이 시점에서 csharpListObjPython의 정수 배열이 있는 완전한 기능의 C# 배열입니다. 그리고 이를 증명하기 위해 콘솔에 모두 나열할 수 있습니다!

Pythonnet을 사용한 목록 출력

콘솔에 인쇄된 숫자는 Python에서 선언되고 Pythonnet에서 C#으로 다시 전달됩니다.

요약

결론적으로 C# .NET Core 애플리케이션 내에서 Python을 사용하는 것은 쉽고 원활합니다. Python for .NET은 Python 인터프리터와 상호 작용하고 Python 함수를 호출하기 위한 많은 메서드를 제공합니다. 이러한 방법을 사용하면 Python의 기능을 활용하여 C# .NET Core 애플리케이션에 새로운 기능을 추가할 수 있습니다. 무엇을 지을 건가요?!

특허

이 문서는 관련 소스 코드 및 파일과 함께 The Code Project Open License(CPOL) 에 따라 사용이 허가되었습니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

작성자
팀장 마이크로소프트
미국 미국
 

Pythonnet – A Simple Union of .NET Core and Python You’ll Love

Rate me:
5.00/5 (10 votes)
25 Jan 2023CPOL3 min read
Use the "Python for .NET" package as a way to call Python from C# code
Python and C# are two very popular languages. As a C# developer primarily, I find there are situations where I would like to interface with Python. Here are examples for using the "Python for .NET" package as a way to call Python from C# code.

Python is a powerful and versatile programming language that has become increasingly popular. For many, it’s one of the very first programming languages they pick up when getting started. Some of the highest traffic posts on my blog many years after they were written look at using C# and Python together. Today, we’re going to explore how you can use Python from inside a C# .NET Core application with much more modern approaches than my original articles. Enter Pythonnet!

Pythonnet Package & Getting Started

We’re going to be looking at Python for .NET in order to accomplish this goal. This library allows you to take advantage of Python installed on the running machine from within your .NET Core applications. You must configure it to point at the corresponding Python DLL that you’d like to use, and after a couple of lines of initialization, you’re off to the races!

Example 1 – Hello World with Pythonnet

To get started, you’ll need to install the pythonnet package from NuGet. Once you’ve done that, you can use the following code to run a Python script from your C# code:

C#
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            using var scope = Py.CreateScope();
            scope.Exec("print('Hello World from Python!')");
        }
    }
}

This code sets our python DLL path on the Runtime, which will be a necessary step. Don’t forget to do this! We must then call PythonEngine.Initialize() and Py.GIL(), which we will want to dispose of later so consider a using statement. We can ask the static Py class to create a scope for us to use, and then leverage the Exec method in order to execute some Python code. In this example, we’re calling the Exec method to run a simple Python script that prints “Hello World from Python!” to the console.

Example 2 – A Pythonnet Calculator!

You can also use the Python C API to call Python functions directly from C# code. To do this, you’ll need to create a C# wrapper for the Python function you want to call. Here’s an example of how you might create a wrapper for a Python function that takes two integers as arguments and returns their sum:

C#
using System;
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: set this based on your python install. this will resolve from
        // your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            // NOTE: this doesn't validate input
            Console.WriteLine("Enter first integer:");
            var firstInt = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter second integer:");
            var secondInt = int.Parse(Console.ReadLine());

            using dynamic scope = Py.CreateScope();
            scope.Exec("def add(a, b): return a + b");
            var sum = scope.add(firstInt, secondInt);
            Console.WriteLine($"Sum: {sum}");
        }
    }
}

In this example, we’re using the Exec method to define a Python function called add that takes two integers as arguments and returns their sum. Thanks to the dynamic keyword in C#, we are able to make an assumption that our scope object has a method called add directly on it. Finally, we use C# code directly to call the add method just like as if it was inside of C#. The return type assigned to the sum variable in C# is also dynamic, but you could declare this variable as an integer and it will compile properly with this type as well.

A calculator output using Pythonnet

The results in the console window from our simple Pythonnet calculator!

Example 3 – Object Interop

We can also pass Python objects to C# functions and vice versa. Here’s an example of how you might receive a Python list back to C# function and iterate over its elements without using the dynamic keyword:

C#
using Python.Runtime;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        // NOTE: Set this based on your Python install. 
        // This will resolve from your PATH environment variable as well.
        Runtime.PythonDLL = "python310.dll";

        PythonEngine.Initialize();
        using (Py.GIL())
        {
            using var scope = Py.CreateScope();

            scope.Exec("number_list = [1, 2, 3, 4, 5]");
            var pythonListObj = scope.Eval("number_list");
            var csharpListObj = pythonListObj.As<int[]>();

            Console.WriteLine("The numbers from python are:");
            foreach (var value in csharpListObj)
            {
                Console.WriteLine(value);
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

In this example, we’re using the Exec method to create a Python list and assign it to a variable called number_list. We then use the Eval method to get a reference to the list object and then we can call As<T> with an integer array (denoted as int[]) to convert the result. At this point, csharpListObj is a fully functional C# array with the array of integers from Python. And to prove it, we can list them all to the console!

A list output using Pythonnet

The numbers printed to the console are declared in Python and passed back to C# from Pythonnet.

Summary

In conclusion, using Python inside C# .NET Core application is easy and seamless. Python for .NET provides many methods for interacting with the Python interpreter and calling Python functions. By using these methods, you can leverage the power of Python to add new functionality in your C# .NET Core applications. What are you going to build?!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 
Written By
Team Leader Microsoft
United States United States
I'm a software engineering professional with a decade of hands-on experience creating software and managing engineering teams. I graduated from the University of Waterloo in Honours Computer Engineering in 2012.

I started blogging at http://www.devleader.ca in order to share my experiences about leadership (especially in a startup environment) and development experience. Since then, I have been trying to create content on various platforms to be able to share information about programming and engineering leadership.
 
[출처] https://www.codeproject.com/Articles/5352648/Pythonnet-A-Simple-Union-of-NET-Core-and-Python-Yo
본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
120 [WPF] Using Images in WPF TabControl Headers 탭컨트롤 헤더 이미지 file 졸리운_곰 2024.02.18 2
119 [Windows Apps][MFC] HTTP SPY : HTTP 스파이 file 졸리운_곰 2023.11.29 3
118 [Windows Apps][MFC] 2D LUA Based Robot Simulator : 2D LUA 기반 로봇 시뮬레이터 file 졸리운_곰 2023.11.29 3
117 [인공지능 VB.NET] Build Simple AI .NET Library - Part 2 - Machine Learning Introduction : 간단한 AI .NET 라이브러리 구축 - 2부 - 기계 학습 소개 file 졸리운_곰 2023.10.19 6
116 [인공지능 VB.NET] Build Simple AI .NET Library - Part 1 - Basics First : 간단한 AI .NET 라이브러리 구축 - 1부 - 기본 사항 우선 file 졸리운_곰 2023.10.19 2
115 [Windows Programming] [VisualStudio] Nuget 패키지소스 URL file 졸리운_곰 2023.09.14 2
114 [Windows Programming] A brief history of Windows UI platforms : Windows UI 플랫폼의 간략한 역사 file 졸리운_곰 2023.09.04 2
113 [C# Apps] Editor3D: A Windows.Forms Render Control with interactive 3D Editor in C# Editor3D: C#의 대화형 3D 편집기가 포함된 Windows.Forms 렌더 컨트롤 file 졸리운_곰 2023.09.03 7
112 [인공지능 (AI)] Logo Recognition System file 졸리운_곰 2023.06.04 3
» [C# app] Pythonnet – .NET Core와 Python의 간단한 결합 : Pythonnet – A Simple Union of .NET Core and Python You’ll Love file 졸리운_곰 2023.03.11 3
110 [C# app] Gidon C# 플러그인 프레임워크에 Python 애플리케이션 포함 : Embedding Python Applications within Gidon C# Plugin Framework file 졸리운_곰 2023.03.07 43
109 [C# App] Gidon - Avalonia 기반 MVVM 플러그인 IoC 컨테이너 : Gidon - Avalonia based MVVM Plugin IoC Container file 졸리운_곰 2023.03.07 4
108 [VS2019] [C#] WinForm에 MySQL 연동하기 file 졸리운_곰 2022.12.25 7
107 [윈도우즈 앱 개발]CaptureManager SDK - Capturing, Recording and Streaming Video and Audio from Web-Cams file 졸리운_곰 2021.04.13 34
106 [ASP.NET] JavaScript 및 ASP.NET 개발자를 위한 Blazor 소개 file 졸리운_곰 2021.03.28 82
105 [c# asp.net core] - gRPC 서버, 클라이언트 샘플 튜토리얼 file 졸리운_곰 2021.02.10 174
104 [C#] sqlite on C# 예제로 배우는 C# 프로그래밍 file 졸리운_곰 2021.01.30 213
103 윈도우 wcript.shell 졸리운_곰 2020.09.10 91
102 WSH(WIndows Script Hosting) 정리 졸리운_곰 2020.09.10 760
101 [VisualBasic] Windows 화면 보호기/절전 모드 방지 방법 졸리운_곰 2020.09.10 342
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED