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)
11150정성태2/21/201719353.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201723060오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201721979.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201721207오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201719902오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201721357.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201724768.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201722115.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201730141.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201724426.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201720170.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201722900.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201721205VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201719875Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201719070오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201720070Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면? [1]
11134정성태1/20/201727451.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201723624.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201735129.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201724005.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201724544.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201728905.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201723297.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201722936기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201727626기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201724490개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...