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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11787정성태11/29/201821821Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201818764오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201821043디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201820289Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201818499오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201817578Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201820956개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201821961오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201822861개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201820180.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201820671오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201818719.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201820472Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201818958Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201818595Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201820522Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201819538사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201828008Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
11769정성태11/5/201818892오류 유형: 501. 프로젝트 msbuild Publish 후 connectionStrings의 문자열이 $(ReplacableToken_...)로 바뀌는 문제
11768정성태11/2/201819384.NET Framework: 801. SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
11767정성태11/1/201820280사물인터넷: 55. New NodeMcu v3(ESP8266)의 IR LED (적외선 송신) 제어파일 다운로드1
11766정성태10/31/201822403사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
11765정성태10/26/201819258개발 환경 구성: 420. Visual Studio Code - Arduino Board Manager를 이용한 사용자 정의 보드 선택
11764정성태10/26/201824166개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리 [2]
11763정성태10/25/201821121사물인터넷: 53. New NodeMcu v3(ESP8266)의 https 통신
11762정성태10/25/201821545사물인터넷: 52. New NodeMCU v3(ESP8266)의 http 통신파일 다운로드1
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...