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

비밀번호

댓글 작성자
 




... 151  [152]  153  154  155  156  157  158  159  160  161  162  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
1253정성태3/1/201228049VS.NET IDE: 71. Visual Studio 11 Ultimate 베타 설치 [3]
1252정성태3/1/201225403Windows: 55. 윈도우 8 베타 설치 과정 [1]
1251정성태2/27/201229347VC++: 60. C/C++ Native 스레드 콜 스택 덤프를 얻는 공개 라이브러리 [2]파일 다운로드1
1250정성태2/27/201231493VC++: 59. C/C++ 프로젝트 빌드 속도 개선 - UnityBuild를 아세요? [3]
1249정성태2/26/201231151.NET Framework: 311. .NET 스레드 콜 스택 덤프 (5) - ICorDebug 인터페이스 사용법 [2]파일 다운로드3
1248정성태2/25/201242638.NET Framework: 310. C#의 Shift 비트 연산 정리파일 다운로드1
1247정성태2/25/201225350.NET Framework: 309. .NET 응용 프로그램에 기본 생성되는 스레드들에 대한 탐구 [1]파일 다운로드1
1246정성태2/25/201224887개발 환경 구성: 145. 한영 변환은 되지만, 정작 한글 입력이 안되는 경우
1245정성태2/25/201235603개발 환경 구성: 144. 윈도우에서도 유닉스처럼 명령행으로 원격 접속하는 방법
1244정성태2/24/201232794.NET Framework: 308. .NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까? [1]파일 다운로드1
1243정성태2/23/201232751개발 환경 구성: 143. Visual Studio 2010 - .NET Framework 소스 코드 디버깅 - 두 번째 이야기 [1]
1242정성태2/20/201239609VC++: 58. API Hooking - 64비트를 고려해야 한다면? EasyHook! [7]파일 다운로드1
1241정성태2/20/201226423.NET Framework: 307. .NET 4.0 응용 프로그램을 위한 ILMerge
1240정성태2/19/201232718디버깅 기술: 48. C/C++ JNI DLL을 Visual Studio로 디버깅하는 방법 [2]
1239정성태2/19/201224370.NET Framework: 306. 컴퓨터에 실행된 프로세스 중에 닷넷 응용 프로그램임을 알 수 있는 방법 - C# [1]파일 다운로드1
1238정성태2/19/201228244.NET Framework: 305. GetPrivateProfileSection / WritePrivateProfileSection의 C# 버전파일 다운로드1
1237정성태2/18/201232564개발 환경 구성: 142. Windows Embedded POSReady 7 설치 [1]
1236정성태2/17/201228405개발 환경 구성: 141. Windows 2008 R2 RDP 라이선스 서버 설치하는 방법
1235정성태2/16/201226804.NET Framework: 304. Hyper-V의 가상 머신을 C#으로 제어하는 방법 [1]파일 다운로드1
1234정성태2/16/201227254.NET Framework: 303. 원본 파일의 공백/라인을 유지한 체 XML 파일을 저장하는 방법 [1]파일 다운로드1
1233정성태2/16/201233346.NET Framework: 302. supportedRuntime 옵션과 System.BadImageFormatException 예외 [5]
1232정성태2/9/201229221VC++: 57. 웹 브라우저에서 Flash만 빼고 다른 ActiveX를 차단할 수 있을까? [3]파일 다운로드1
1231정성태2/8/201238737VC++: 56. Win32 API 후킹 - Trampoline API Hooking [5]파일 다운로드1
1230정성태2/6/201224078개발 환경 구성: 140. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법
1229정성태2/4/201229099.NET Framework: 301. P/Invoke의 성능을 높이기 위해 C++/CLI가 선택되려면? [5]파일 다운로드1
1228정성태2/4/201278431.NET Framework: 300. C#으로 만드는 음성인식/TTS 프로그램 [47]파일 다운로드1
... 151  [152]  153  154  155  156  157  158  159  160  161  162  163  164  165  ...