ModuleFromString() public static method

ModuleFromString Method
Given a string module name and a string containing Python code, execute the code in and return a module of the given name.
public static ModuleFromString ( string name, string code ) : PyObject
name string
code string
return PyObject
コード例 #1
0
        static Converter()
        {
            nfi         = NumberFormatInfo.InvariantInfo;
            objectType  = typeof(Object);
            stringType  = typeof(String);
            int16Type   = typeof(Int16);
            int32Type   = typeof(Int32);
            int64Type   = typeof(Int64);
            singleType  = typeof(Single);
            doubleType  = typeof(Double);
            decimalType = typeof(Decimal);
            flagsType   = typeof(FlagsAttribute);
            boolType    = typeof(Boolean);
            typeType    = typeof(Type);

            IntPtr dateTimeMod = Runtime.PyImport_ImportModule("datetime");

            if (dateTimeMod == null)
            {
                throw new PythonException();
            }

            dateTimeCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "datetime");
            if (dateTimeCtor == null)
            {
                throw new PythonException();
            }

            timeSpanCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "timedelta");
            if (timeSpanCtor == null)
            {
                throw new PythonException();
            }

            IntPtr tzInfoMod = PythonEngine.ModuleFromString("custom_tzinfo", @"
from datetime import timedelta, tzinfo
class GMT(tzinfo):
    def __init__(self, hours, minutes):
        self.hours = hours
        self.minutes = minutes
    def utcoffset(self, dt):
        return timedelta(hours=self.hours, minutes=self.minutes)
    def tzname(self, dt):
        return f'GMT {self.hours:00}:{self.minutes:00}'
    def dst (self, dt):
        return timedelta(0)").Handle;

            tzInfoCtor = Runtime.PyObject_GetAttrString(tzInfoMod, "GMT");
            if (tzInfoCtor == null)
            {
                throw new PythonException();
            }
        }