Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# - Python.NET의 RunSimpleScript, Exec, Eval 차이점

Python.NET을 사용하는 경우,

C# - Python.NET을 이용한 파이썬 소스코드 연동
; https://www.sysnet.pe.kr/2/0/13605

스크립트 실행 방식이 4가지가 있습니다. 우선 (deprecated로 표시된) RunString이 있는데요,

using Python.Runtime;

internal class Program
{
    // Install-Package pythonnet
    static void Main(string[] args)
    {
        string script = File.ReadAllText("test.py");

        Runtime.PythonDLL = @"E:\Python3133\embed\python313.dll";
        PythonEngine.Initialize();

        PyDict globalDict = new PyDict();
        PyDict localDict = new PyDict();

        using (_ = Py.GIL())
        {
            PythonEngine.RunString(script, globalDict, localDict);
        }

        PythonEngine.Shutdown();
    }
}

현재는 RunSimpleString이 그 역할을 이어가고 있습니다.

// PythonEngine.RunString(script, globalDict, localDict);

PythonEngine.RunSimpleString(script);

차이점이라면 global dict와 local dict를 사용할 수 없다는 건데요, 이게 필요하다면 Exec 버전을 사용하면 됩니다. 예를 들어, 파이썬 소스 코드가 다음과 같을 때,

print('test')

def my_func(a, b):
    return a + b

Exec 버전을 사용하면,

PythonEngine.Exec(script, globalDict, localDict); // 화면에 "test" 출력
dynamic my_func = localDict.GetItem("my_func");
Console.WriteLine(my_func(5, 6)); // 출력: 11

해당 스크립트가 실행되면서 함께 전달했던 globalDict/localDict로 파이썬 스크립트 내부의 개체와 연동할 수 있습니다





RunSimpleString과 Exec에는 또 다른 차이점이 하나 더 존재하는데요, 예를 들어, 아래의 코드는 python으로 실행 시, 또는 PythonEngine.RunSimpleString으로 실행하면 정상적으로 작동하지만,

C:\temp> type test.py

import os


def get_current_dir():
    return os.getcwd()


print('getcwd:', get_current_dir())


C:\temp> python test.py
getcwd: C:\temp

PythonEngine.Exec을 통해 실행하면 이런 오류가 발생합니다.

PythonEngine.Exec(script, globalDict, localDict);

/*
Unhandled exception. Python.Runtime.PythonException: name 'os' is not defined
  File "<string>", line 6, in get_current_dir
  File "<string>", line 9, in <module>
   at Python.Runtime.PythonException.ThrowLastAsClrException()
   at Python.Runtime.PythonException.ThrowIfIsNull(NewReference& ob)
   at Python.Runtime.PythonEngine.RunString(String code, BorrowedReference globals, BorrowedReference locals, RunFlagType flag)
   at Python.Runtime.PythonEngine.Exec(String code, PyDict globals, PyObject locals)
   at Program.Main(String[] args) in C:\temp\ConsoleApp1\ConsoleApp1\Program.cs:line 34
*/

재미있는 건, Exec의 경우에도 PyDict(globa/local)를 넘기지 않는다면 정상적으로 실행이 됩니다.

PythonEngine.Exec(script); // "name '...' is not defined" 오류 없이 정상적으로 실행됨

이게 의도한 것인지, 버그인지는 잘 모르겠습니다. 만약 Exec의 버전에서 꼭 PyDict(globa/local) 문맥이 필요하다면 파이썬 소스 코드를 이런 식으로 수정하거나,

import os


def get_current_dir():
    global os
    return os.getcwd()


print('getcwd:', get_current_dir())

아예 import를 get_current_dir 함수 내에서 하면 됩니다.

def get_current_dir():
    import os
    return os.getcwd()




마지막으로 Exec와 Eval의 차이점은 파이썬 본래의 exec/eval과 유사합니다. Exec의 경우 반환값이 없는 메서드이면서 스크립트에 문(statement)을 포함할 수 있는데요, 반면 Eval은 스크립트에 "식(expression)"만 포함할 수 있지만 대신 그 식의 평가값을 메서드가 반환합니다.

Console.WriteLine(PythonEngine.Eval("5 + 6")); // 출력: 11

또한 Exec처럼 globalDict/localDict를 사용할 수 있기 때문에 문맥을 공유해 실행하는 것도 가능합니다.

/* # script.py
def my_func(a, b):
    return a + b
*/
PythonEngine.Exec(script, globalDict, localDict); // Exec로 실행된 환경의 global/local 문맥으로,

// Eval 함수에서 재사용
var retValue = PythonEngine.Eval("my_func(5, 6)", globalDict, localDict);
Console.WriteLine(retValue); // 출력: 11




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/5/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...
NoWriterDateCnt.TitleFile(s)
10975정성태5/20/201623342Math: 17. C# - 복소수 타입의 승수를 지원하는 Power 메서드파일 다운로드1
10974정성태5/20/201623838.NET Framework: 588. C# - OxyPlot 라이브러리로 복소수 표현파일 다운로드1
10973정성태5/20/201628889.NET Framework: 587. C# Plotting 라이브러리 OxyPlot [3]파일 다운로드1
10972정성태5/19/201627926Math: 16. C# - 갈루아 필드 GF(2) 연산 [3]파일 다운로드1
10971정성태5/19/201620735오류 유형: 334. Visual Studio - 빌드 시 경고 warning MSB3884: Could not find rule set file "...". [2]
10970정성태5/19/201625161오류 유형: 333. OxyPlot 라이브러리의 컨트롤을 Toolbox에 등록 시 오류 [2]
10969정성태5/18/201624356.NET Framework: 586. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (3) - "Open with" 목록에 등록파일 다운로드1
10968정성태5/18/201619388오류 유형: 332. Visual Studio - 단위 테스트 생성 시 "Design time expression evaluation" 오류 메시지
10967정성태5/12/201624511.NET Framework: 585. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (2) - 웹 브라우저가 다운로드 후 자동 실행
10966정성태5/12/201632138.NET Framework: 584. C# - 파일 확장자에 연결된 프로그램을 등록하는 방법 (1) - 기본 [1]파일 다운로드1
10965정성태5/12/201624168디버깅 기술: 81. try/catch로 조용히 사라진 예외를 파악하고 싶다면?
10964정성태5/12/201622724오류 유형: 331. ASP.NET에서 System.BadImageFormatException 예외가 발생하는 경우
10963정성태5/11/201625000VS.NET IDE: 107. Visual Studio 2015의 "DTAR_..." 특수 폴더가 생성되는 문제파일 다운로드2
10962정성태5/11/201625038오류 유형: 330. Visual Studio 단위 테스트 시 DisconnectedContext 예외 발생
10961정성태5/11/201624915.NET Framework: 583. 문제 재현 - Managed Debugging Assistant 'DisconnectedContext' has detected a problem in '...'파일 다운로드1
10960정성태5/10/201622410오류 유형: 329. ATL 메서드 추가 마법사 창에서 8ce0000b 오류 발생
10959정성태5/9/201624958.NET Framework: 582. CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경파일 다운로드1
10958정성태5/6/201651927개발 환경 구성: 284. "Let's Encrypt"에서 제공하는 무료 SSL 인증서를 IIS에 적용하는 방법 (1) [3]
10957정성태5/3/201627242오류 유형: 328. 윈도우 백업 시 오류 - 0x80780166 두 번째 이야기 [1]
10956정성태5/3/201622798Windows: 117. BitLocker - This device can't use a Trusted Platform Module.
10955정성태5/3/201629438.NET Framework: 581. C# - 순열(Permutation) 예제 코드파일 다운로드2
10954정성태5/3/201630411.NET Framework: 580. C# - 조합(Combination) 예제 코드 [2]파일 다운로드1
10953정성태5/2/201619969.NET Framework: 579. Assembly.LoadFrom으로 로드된 어셈블리의 JIT 컴파일 코드 공유?파일 다운로드1
10952정성태5/2/201622122.NET Framework: 578. 도메인 중립적인 어셈블리가 비-도메인 중립적인 어셈블리를 참조하는 경우파일 다운로드1
10951정성태5/2/201619973.NET Framework: 577. CLR Profiler로 살펴보는 SharedDomain의 모듈 로드 동작파일 다운로드1
10950정성태5/2/201626463.NET Framework: 576. 기본적인 CLR Profiler 소스 코드 설명 [2]파일 다운로드2
... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...