public _FileIO(CodeContext/*!*/ context, int fd, [DefaultParameterValue("r")]string mode, [DefaultParameterValue(true)]bool closefd) { if (fd < 0) { throw PythonOps.ValueError("fd must be >= 0"); } PythonContext pc = PythonContext.GetContext(context); _FileIO file = (_FileIO)pc.FileManager.GetObjectFromId(pc, fd); Console.WriteLine(file); _context = pc; switch (mode) { case "r": _mode = "rb"; break; case "w": _mode = "wb"; break; case "a": _mode = "w"; break; case "r+": case "+r": _mode = "rb+"; break; case "w+": case "+w": _mode = "rb+"; break; case "a+": case "+a": _mode = "r+"; break; default: BadMode(mode); break; } _readStream = file._readStream; _writeStream = file._writeStream; _closefd = closefd; }
public static void PerformModuleReload(PythonContext/*!*/ context, IDictionary/*!*/ dict) { if (ucd_5_2_0 == null) { // This is a lie. The version of Unicode depends on the .NET version as well as the OS. The // version of the database stored internally is 5.2, so just say that. Interlocked.CompareExchange(ref ucd_5_2_0, new UCD("5.2.0"), null); } }
public CodeContext(Scope scope, PythonContext languageContext, CodeContext parent) { Assert.NotNull(languageContext); _languageContext = languageContext; _scope = scope; _parent = parent; }
public static void PerformModuleReload(PythonContext context, PythonDictionary dict) { if (!context.HasModuleState(_zip_directory_cache_key)) context.SetModuleState(_zip_directory_cache_key, new PythonDictionary()); dict["_zip_directory_cache"] = context.GetModuleState(_zip_directory_cache_key); InitModuleExceptions(context, dict); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { var socket = context.GetBuiltinModule("socket"); var socketError = PythonSocket.GetSocketError(context, socket.__dict__); context.EnsureModuleException("SSLError", socketError, dict, "SSLError", "ssl"); }
public static void PerformModuleReload(PythonContext context, PythonDictionary dict) { PythonModule scope = Importer.ImportModule(context.SharedContext, context.SharedContext.GlobalDict, "itertools", false, -1) as PythonModule; if (scope != null) { dict["map"] = scope.__dict__["imap"]; dict["filter"] = scope.__dict__["ifilter"]; dict["zip"] = scope.__dict__["izip"]; } }
public static void PerformModuleReload(PythonContext context, IAttributesCollection dict) { PythonModule scope = Importer.ImportModule(context.SharedContext, context.SharedContext.GlobalDict, "itertools", false, -1) as PythonModule; if (scope != null) { dict[SymbolTable.StringToId("map")] = scope.__dict__["imap"]; dict[SymbolTable.StringToId("filter")] = scope.__dict__["ifilter"]; dict[SymbolTable.StringToId("zip")] = scope.__dict__["izip"]; } }
private static PythonSignalState MakeSignalState(PythonContext context) { if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { return MakePosixSignalState(context); } else { return MakeNtSignalState(context); } }
/// <summary> /// Runs the formatting operation on the given format and keyword arguments /// </summary> public static string/*!*/ FormatString(PythonContext/*!*/ context, string/*!*/ format, PythonTuple/*!*/ args, IAttributesCollection/*!*/ kwArgs) { ContractUtils.RequiresNotNull(context, "context"); ContractUtils.RequiresNotNull(format, "format"); ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(kwArgs, "kwArgs"); return Formatter.FormatString(context, format, args, kwArgs); }
public static void PerformModuleReload(PythonContext context, IAttributesCollection dict) { Scope scope = Importer.ImportModule(context.SharedContext, context.SharedContext.GlobalScope.Dict, "itertools", false, -1) as Scope; if (scope != null) { dict[SymbolTable.StringToId("map")] = scope.LookupName(context, SymbolTable.StringToId("imap")); dict[SymbolTable.StringToId("filter")] = scope.LookupName(context, SymbolTable.StringToId("ifilter")); dict[SymbolTable.StringToId("zip")] = scope.LookupName(context, SymbolTable.StringToId("izip")); } }
public static void PerformModuleReload(PythonContext/*!*/ context, IAttributesCollection/*!*/ dict) { context.EnsureModuleException("PickleError", dict, "PickleError", "cPickle"); context.EnsureModuleException("PicklingError", dict, "PicklingError", "cPickle"); context.EnsureModuleException("UnpicklingError", dict, "UnpicklingError", "cPickle"); context.EnsureModuleException("UnpickleableError", dict, "UnpickleableError", "cPickle"); context.EnsureModuleException("BadPickleGet", dict, "BadPickleGet", "cPickle"); dict[Symbols.Builtins] = context.BuiltinModuleInstance; dict[SymbolTable.StringToId("compatible_formats")] = PythonOps.MakeList("1.0", "1.1", "1.2", "1.3", "2.0"); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("PickleError", dict, "PickleError", "cPickle"); context.EnsureModuleException("PicklingError", dict, "PicklingError", "cPickle"); context.EnsureModuleException("UnpicklingError", dict, "UnpicklingError", "cPickle"); context.EnsureModuleException("UnpickleableError", dict, "UnpickleableError", "cPickle"); context.EnsureModuleException("BadPickleGet", dict, "BadPickleGet", "cPickle"); dict["__builtins__"] = context.BuiltinModuleInstance; dict["compatible_formats"] = PythonOps.MakeList("1.0", "1.1", "1.2", "1.3", "2.0"); }
/// <summary> /// Creates a new ModuleContext for the specified module. /// </summary> public ModuleContext(PythonModule/*!*/ module, PythonContext/*!*/ creatingContext) { ContractUtils.RequiresNotNull(module, "module"); ContractUtils.RequiresNotNull(creatingContext, "creatingContext"); _globals = module.__dict__; _pyContext = creatingContext; _globalContext = new CodeContext(_globals, this); _module = module; }
public StaticGlobalAllocator(PythonContext/*!*/ context, string name) { _typeGen = Snippets.Shared.DefineType(name, typeof(object), false, false); _codeContextField = _typeGen.AddStaticField(typeof(CodeContext), "__global_context"); _codeContext = CreateFieldBuilderExpression(_codeContextField); _scope = new Scope(new PythonDictionary(new GlobalDictionaryStorage(_globalVals))); _context = new CodeContext(_scope, context); }
private static void InitModuleExceptions(PythonContext context, PythonDictionary dict) { ZipImportError = context.EnsureModuleException( "zipimport.ZipImportError", PythonExceptions.ImportError, typeof(PythonExceptions.BaseException), dict, "ZipImportError", "zipimport", msg => new ImportException(msg)); }
/// <summary> /// Creates a new ModuleContext which is backed by the specified dictionary. /// </summary> public ModuleContext(PythonDictionary/*!*/ globals, PythonContext/*!*/ creatingContext) { ContractUtils.RequiresNotNull(globals, "globals"); ContractUtils.RequiresNotNull(creatingContext, "creatingContext"); _globals = globals; _pyContext = creatingContext; _globalContext = new CodeContext(globals, this); _module = new PythonModule(globals); _module.Scope.SetExtension(_pyContext.ContextId, new PythonScopeExtension(_pyContext, _module, this)); }
public static void PerformModuleReload(PythonContext/*!*/ context, IAttributesCollection/*!*/ dict) { dict.Add(SymbolTable.StringToId(_keyDefaultAction), "default"); dict.Add(SymbolTable.StringToId(_keyOnceRegistry), new PythonDictionary()); dict.Add(SymbolTable.StringToId(_keyFilters), new List() { // Default filters PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0) }); context.SetModuleState(_keyFields, dict); }
/// <summary> /// Constructor used to create a FunctionCode for code that's been serialized to disk. /// /// Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// </summary> internal FunctionCode(PythonContext context, Delegate code, Compiler.Ast.ScopeStatement scope, string documentation, int localCount) { _normalDelegate = code; _lambda = scope; _argCount = CalculateArgumentCount(); // need to take this lock to ensure sys.settrace/sys.setprofile is not actively changing lock (_CodeCreateAndUpdateDelegateLock) { Target = AddRecursionCheck(context, code); } RegisterFunctionCode(context); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { if (!context.HasModuleState(_defaultTimeoutKey)) { context.SetModuleState(_defaultTimeoutKey, null); } context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize); PythonType socketErr = GetSocketError(context, dict); context.EnsureModuleException("socketherror", socketErr, dict, "herror", "socket"); context.EnsureModuleException("socketgaierror", socketErr, dict, "gaierror", "socket"); context.EnsureModuleException("sockettimeout", socketErr, dict, "timeout", "socket"); }
public static void PerformModuleReload(PythonContext/*!*/ context, IAttributesCollection/*!*/ dict) { if (!context.HasModuleState(_defaultTimeoutKey)) { context.SetModuleState(_defaultTimeoutKey, null); } context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize); context.EnsureModuleException("sslerror", dict, "sslerror", "socket"); PythonType socketErr = context.EnsureModuleException("socketerror", PythonExceptions.IOError, dict, "error", "socket"); context.EnsureModuleException("socketherror", socketErr, dict, "herror", "socket"); context.EnsureModuleException("socketgaierror", socketErr, dict, "gaierror", "socket"); context.EnsureModuleException("sockettimeout", socketErr, dict, "timeout", "socket"); }
private static void InitModuleExceptions(PythonContext context, PythonDictionary dict) { Warning = context.EnsureModuleException("sqlite.Warning", PythonExceptions.StandardError, dict, "Warning", "_sqlite3"); Error = context.EnsureModuleException("sqlite.Error", PythonExceptions.StandardError, dict, "Error", "_sqlite3"); InterfaceError = context.EnsureModuleException("sqlite.InterfaceError", Error, dict, "InterfaceError", "_sqlite3"); DatabaseError = context.EnsureModuleException("sqlite.DatabaseError", Error, dict, "DatabaseError", "_sqlite3"); DataError = context.EnsureModuleException("sqlite.DataError", DatabaseError, dict, "DataError", "_sqlite3"); OperationalError = context.EnsureModuleException("sqlite.OperationalError", DatabaseError, dict, "OperationalError", "_sqlite3"); IntegrityError = context.EnsureModuleException("sqlite.IntegrityError", DatabaseError, dict, "IntegrityError", "_sqlite3"); InternalError = context.EnsureModuleException("sqlite.InternalError", DatabaseError, dict, "InternalError", "_sqlite3"); ProgrammingError = context.EnsureModuleException("sqlite.ProgrammingError", DatabaseError, dict, "ProgrammingError", "_sqlite3"); NotSupportedError = context.EnsureModuleException("sqlite.NotSupportedError", DatabaseError, dict, "NotSupportedError", "_sqlite3"); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, new List() { // Default filters PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0), PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0) }); return dict; }); }
public static void PerformModuleReload(PythonContext context, PythonDictionary dict) { if (!context.HasModuleState(_fieldSizeLimitKey)) { context.SetModuleState(_fieldSizeLimitKey, FieldSizeLimit); } if (!context.HasModuleState(_dialectRegistryKey)) { context.SetModuleState(_dialectRegistryKey, new DialectRegistry()); } InitModuleExceptions(context, dict); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { List defaultFilters = new List(); if (context.PythonOptions.WarnPython30) { defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.DeprecationWarning, null, 0)); } defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.PendingDeprecationWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.ImportWarning, null, 0)); defaultFilters.AddNoLock(PythonTuple.MakeTuple("ignore", null, PythonExceptions.BytesWarning, null, 0)); context.GetOrCreateModuleState(_keyFields, () => { dict.Add(_keyDefaultAction, "default"); dict.Add(_keyOnceRegistry, new PythonDictionary()); dict.Add(_keyFilters, defaultFilters); return dict; }); }
public static void PerformModuleReload(PythonContext/*!*/ context, IAttributesCollection/*!*/ dict) { context.EnsureModuleException("ArgumentError", dict, "ArgumentError", "_ctypes"); context.EnsureModuleException("COMError", dict, "COMError", "_ctypes"); // TODO: Provide an implementation which is coordinated with our _refCountTable context.SystemState.__dict__["getrefcount"] = null; PythonDictionary pointerTypeCache = new PythonDictionary(); dict[SymbolTable.StringToId("_pointer_type_cache")] = pointerTypeCache; context.SetModuleState(_pointerTypeCacheKey, pointerTypeCache); if (Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE) { context.SetModuleState(_conversion_mode, PythonTuple.MakeTuple("mbcs", "ignore")); } else { context.SetModuleState(_conversion_mode, PythonTuple.MakeTuple("ascii", "strict")); } }
/// <summary> /// Constructor used to create a FunctionCode for code that's been serialized to disk. /// /// Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. /// /// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. /// </summary> internal FunctionCode(PythonContext context, Delegate code, string name, string documentation, string[] argNames, FunctionAttributes flags, SourceSpan span, string path, string[] freeVars, string[] names, string[] cellVars, string[] varNames, int localCount) { _name = name; _span = span; _initialDoc = documentation; _argNames = argNames; _flags = flags; _span = span; _filename = path; _freevars = StringArrayToTuple(freeVars); _names = StringArrayToTuple(names); _cellvars = StringArrayToTuple(cellVars); _varnames = StringArrayToTuple(varNames); _localCount = localCount; _normalDelegate = code; // need to take this lock to ensure sys.settrace/sys.setprofile is not actively changing lock (_CodeCreateAndUpdateDelegateLock) { Target = AddRecursionCheck(context, code); } RegisterFunctionCode(context); }
private static object fromkeysAny(CodeContext /*!*/ context, PythonType cls, object o, object value) { PythonDictionary pyDict; object dict; if (cls == TypeCache.Dict) { string str; ICollection ic = o as ICollection; // creating our own dict, try and get the ideal size and add w/o locks if (ic != null) { pyDict = new PythonDictionary(new CommonDictionaryStorage(ic.Count)); } else if ((str = o as string) != null) { pyDict = new PythonDictionary(str.Length); } else { pyDict = new PythonDictionary(); } IEnumerator i = PythonOps.GetEnumerator(o); while (i.MoveNext()) { pyDict._storage.AddNoLock(i.Current, value); } return(pyDict); } else { // call the user type constructor dict = MakeDict(context, cls); pyDict = dict as PythonDictionary; } if (pyDict != null) { // then store all the keys with their associated value IEnumerator i = PythonOps.GetEnumerator(o); while (i.MoveNext()) { pyDict[i.Current] = value; } } else { // slow path, cls.__new__ returned a user defined dictionary instead of a PythonDictionary. PythonContext pc = PythonContext.GetContext(context); IEnumerator i = PythonOps.GetEnumerator(o); while (i.MoveNext()) { pc.SetIndex(dict, i.Current, value); } } return(dict); }
/// <summary> /// Get the unique Profiler instance for this ScriptRuntime /// </summary> public static Profiler GetProfiler(PythonContext /*!*/ context) { return(context.GetOrCreateModuleState(_profileKey, () => new Profiler())); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.SetModuleState(_stackSizeKey, 0); context.EnsureModuleException("threaderror", dict, "error", "thread"); }
private static PythonModule /*!*/ LoadFromSourceUnit(CodeContext /*!*/ context, SourceUnit /*!*/ sourceCode, string /*!*/ name, string /*!*/ path) { Assert.NotNull(sourceCode, name, path); return(PythonContext.GetContext(context).CompileModule(path, name, sourceCode, ModuleOptions.Initialize | ModuleOptions.Optimized)); }
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { PythonSignalState pss = new PythonSignalState(context); context.SetModuleState(_PythonSignalStateKey, pss); NativeSignal.SetConsoleCtrlHandler(pss.WinAllSignalsHandlerDelegate, true); }
public PythonSignalState(PythonContext pc) { SignalPythonContext = pc; WinAllSignalsHandlerDelegate = new NativeSignal.WinSignalsHandler(WindowsEventHandler); PySignalToPyHandler = new Dictionary<int, object>() { { SIGABRT, SIG_DFL}, { SIGBREAK, SIG_DFL}, { SIGFPE, SIG_DFL}, { SIGILL, SIG_DFL}, { SIGINT, default_int_handler}, { SIGSEGV, SIG_DFL}, { SIGTERM, SIG_DFL}, }; }
public static PythonType CreateSubType(PythonContext/*!*/ context, PythonType baseType, string name, string module, string documentation) { PythonType res = new PythonType(context, baseType, name, module, documentation); res.SetCustomMember(context.SharedContext, "__weakref__", new PythonTypeWeakRefSlot(res)); res.IsWeakReferencable = true; return res; }
/// <summary> /// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py) /// /// level indiciates whether to perform absolute or relative imports. /// -1 indicates both should be performed /// 0 indicates only absolute imports should be performed /// Positive numbers indicate the # of parent directories to search relative to the calling module /// </summary> public static object ImportModule(CodeContext /*!*/ context, object globals, string /*!*/ modName, bool bottom, int level) { if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) { throw PythonOps.ImportError("Import by filename is not supported.", modName); } //Debug.WriteLine("Importing: " + modName); string package = null; object attribute; PythonDictionary pyGlobals = globals as PythonDictionary; if (pyGlobals != null) { if (pyGlobals._storage.TryGetPackage(out attribute)) { package = attribute as string; if (package == null && attribute != null) { throw PythonOps.ValueError("__package__ set to non-string"); } } else { package = null; if (level > 0) { // explicit relative import, calculate and store __package__ object pathAttr, nameAttr; if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) { if (pyGlobals._storage.TryGetPath(out pathAttr)) { pyGlobals["__package__"] = nameAttr; } else { pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0]; } } } } } object newmod = null; string firstName; int firstDot = modName.IndexOf('.'); if (firstDot == -1) { firstName = modName; } else { firstName = modName.Substring(0, firstDot); } string finalName = null; if (level != 0) { // try a relative import //Debug.WriteLine("Trying a relative import"); // if importing a.b.c, import "a" first and then import b.c from a string name; // name of the module we are to import in relation to the current module PythonModule parentModule; List path; // path to search if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) { finalName = name; // import relative //Debug.WriteLine("Importing relative"); if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod)) { newmod = ImportFromPath(context, firstName, name, path); if (newmod == null) { //Debug.WriteLine("Adding an indirection entry saying this module does not exist"); // add an indirection entry saying this module does not exist // see http://www.python.org/doc/essays/packages.html "Dummy Entries" context.LanguageContext.SystemStateModules[name] = null; } else if (parentModule != null) { //Debug.WriteLine("Setting newmod in dcit"); parentModule.__dict__[modName] = newmod; } } else if (firstDot == -1) { // if we imported before having the assembly // loaded and then loaded the assembly we want // to make the assembly available now. //Debug.WriteLine("If imported before having assembly then making assembly now"); if (newmod is NamespaceTracker) { //Debug.WriteLine("Newmod is NamespaceTracker"); context.ShowCls = true; } } } } if (level <= 0) { // try an absolute import //Debug.WriteLine("Trying an absolute import"); if (newmod == null) { //Debug.WriteLine("newmod is null"); object parentPkg; if (!String.IsNullOrEmpty(package) && !PythonContext.GetContext(context).SystemStateModules.TryGetValue(package, out parentPkg)) { PythonModule warnModule = new PythonModule(); warnModule.__dict__["__file__"] = package; warnModule.__dict__["__name__"] = package; ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext); PythonOps.Warn( modContext.GlobalContext, PythonExceptions.RuntimeWarning, "Parent module '{0}' not found while handling absolute import", package); } //Debug.WriteLine("ImportTopAbsolute: " + context.ToString() + ", " + firstName); newmod = ImportTopAbsolute(context, firstName); finalName = firstName; if (newmod == null) { return(null); } } } // now import the a.b.c etc. a needs to be included here // because the process of importing could have modified // sys.modules. string[] parts = modName.Split('.'); object next = newmod; string curName = null; for (int i = 0; i < parts.Length; i++) { curName = i == 0 ? finalName : curName + "." + parts[i]; object tmpNext; if (TryGetExistingModule(context, curName, out tmpNext)) { next = tmpNext; if (i == 0) { // need to update newmod if we pulled it out of sys.modules // just in case we're in bottom mode. newmod = next; } } else if (i != 0) { // child module isn't loaded yet, import it. next = ImportModuleFrom(context, next, parts[i]); } else { // top-level module doesn't exist in sys.modules, probably // came from some weird meta path hook. newmod = next; } } return(bottom ? next : newmod); }
/// <summary> /// Interrogates the importing module for __name__ and __path__, which determine /// whether the imported module (whose name is 'name') is being imported as nested /// module (__path__ is present) or as sibling. /// /// For sibling import, the full name of the imported module is parent.sibling /// For nested import, the full name of the imported module is parent.module.nested /// where parent.module is the mod.__name__ /// </summary> /// <param name="context"></param> /// <param name="globals">the globals dictionary</param> /// <param name="name">Name of the module to be imported</param> /// <param name="full">Output - full name of the module being imported</param> /// <param name="path">Path to use to search for "full"</param> /// <param name="level">the import level for relaive imports</param> /// <param name="parentMod">the parent module</param> /// <param name="package">the global __package__ value</param> /// <returns></returns> private static bool TryGetNameAndPath(CodeContext /*!*/ context, object globals, string name, int level, string package, out string full, out List path, out PythonModule parentMod) { Debug.Assert(level != 0); // shouldn't be here for absolute imports // Unless we can find enough information to perform relative import, // we are going to import the module whose name we got full = name; path = null; parentMod = null; // We need to get __name__ to find the name of the imported module. // If absent, fall back to absolute import object attribute; PythonDictionary pyGlobals = globals as PythonDictionary; if (pyGlobals == null || !pyGlobals._storage.TryGetName(out attribute)) { return(false); } // And the __name__ needs to be string string modName = attribute as string; if (modName == null) { return(false); } string pn; if (package == null) { // If the module has __path__ (and __path__ is list), nested module is being imported // otherwise, importing sibling to the importing module if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as List) != null) { // found __path__, importing nested module. The actual name of the nested module // is the name of the mod plus the name of the imported module if (level == -1) { // absolute import of some module full = modName + "." + name; object parentModule; if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(modName, out parentModule)) { parentMod = parentModule as PythonModule; } } else if (String.IsNullOrEmpty(name)) { // relative import of ancestor full = (StringOps.rsplit(modName, ".", level - 1)[0] as string); } else { // relative import of some ancestors child string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string); full = parentName + "." + name; object parentModule; if (PythonContext.GetContext(context).SystemStateModules.TryGetValue(parentName, out parentModule)) { parentMod = parentModule as PythonModule; } } return(true); } // importing sibling. The name of the imported module replaces // the last element in the importing module name int lastDot = modName.LastIndexOf('.'); if (lastDot == -1) { // name doesn't include dot, only absolute import possible if (level > 0) { throw PythonOps.ValueError("Attempted relative import in non-package"); } return(false); } // need to remove more than one name int tmpLevel = level; while (tmpLevel > 1 && lastDot != -1) { lastDot = modName.LastIndexOf('.', lastDot - 1); tmpLevel--; } if (lastDot == -1) { pn = modName; } else { pn = modName.Substring(0, lastDot); } } else { // __package__ doesn't include module name, so level is - 1. pn = GetParentPackageName(level - 1, package.Split('.')); } path = GetParentPathAndModule(context, pn, out parentMod); if (path != null) { if (String.IsNullOrEmpty(name)) { full = pn; } else { full = pn + "." + name; } return(true); } if (level > 0) { throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn); } // not enough information - absolute import return(false); }
internal static object ReloadModule(CodeContext /*!*/ context, PythonModule /*!*/ module, PythonFile file) { PythonContext pc = PythonContext.GetContext(context); // We created the module and it only contains Python code. If the user changes // __file__ we'll reload from that file. string fileName = module.GetFile() as string; // built-in module: if (fileName == null) { ReloadBuiltinModule(context, module); return(module); } string name = module.GetName() as string; if (name != null) { List path = null; // find the parent module and get it's __path__ property int dotIndex = name.LastIndexOf('.'); if (dotIndex != -1) { PythonModule parentModule; path = GetParentPathAndModule(context, name.Substring(0, dotIndex), out parentModule); } object reloaded; if (TryLoadMetaPathModule(context, module.GetName() as string, path, out reloaded) && reloaded != null) { return(module); } List sysPath; if (PythonContext.GetContext(context).TryGetSystemPath(out sysPath)) { object ret = ImportFromPathHook(context, name, name, sysPath, null); if (ret != null) { return(ret); } } } SourceUnit sourceUnit; if (file != null) { sourceUnit = pc.CreateSourceUnit(new PythonFileStreamContentProvider(file), fileName, file.Encoding, SourceCodeKind.File); } else { if (!pc.DomainManager.Platform.FileExists(fileName)) { throw PythonOps.SystemError("module source file not found"); } sourceUnit = pc.CreateFileUnit(fileName, pc.DefaultEncoding, SourceCodeKind.File); } pc.GetScriptCode(sourceUnit, name, ModuleOptions.None, Compiler.CompilationMode.Lookup).Run(module.Scope); return(module); }
private static object ImportTopAbsolute(CodeContext /*!*/ context, string /*!*/ name) { //Debug.WriteLine("Importing step 4: " + name); object ret; //Debug.WriteLine("TryGetExistingModule"); if (TryGetExistingModule(context, name, out ret)) { //Debug.WriteLine("Getting existing module"); if (IsReflected(ret)) { // Even though we found something in sys.modules, we need to check if a // clr.AddReference has invalidated it. So try ImportReflected again. ret = ImportReflected(context, name) ?? ret; //Debug.WriteLine("Import refelected"); } NamespaceTracker rp = ret as NamespaceTracker; if (rp != null || ret == PythonContext.GetContext(context).ClrModule) { context.ShowCls = true; } //Debug.WriteLine("Got existing module"); return(ret); } //Debug.WriteLine("TryLoadMetaPathModule"); if (TryLoadMetaPathModule(context, name, null, out ret)) { //Debug.WriteLine("LoadMetaPathModule"); return(ret); } //Debug.WriteLine("Importing builtin"); ret = ImportBuiltin(context, name); if (ret != null) { return(ret); /*Debug.WriteLine("Imported builtin");*/ } List path; //Debug.WriteLine("Trygetsyspath"); if (PythonContext.GetContext(context).TryGetSystemPath(out path)) { //Debug.WriteLine("Importing from path"); ret = ImportFromPath(context, name, name, path); if (ret != null) { return(ret); /*Debug.WriteLine("Imported from path");*/ } } //Debug.WriteLine("Importing refelcted"); ret = ImportReflected(context, name); if (ret != null) { return(ret); /*Debug.WriteLine("Imported reflected");*/ } //Debug.WriteLine("Returning null"); return(null); }
public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { return(GetMemberWorker(binder, PythonContext.GetCodeContextMO(binder))); }
/// <summary> /// Creates a new module backed by a Scope. Used for creating modules for foreign Scope's. /// </summary> internal PythonModule(PythonContext context, Scope scope) { _dict = new PythonDictionary(new ScopeDictionaryStorage(context, scope)); _scope = scope; }
public PythonDocumentationProvider(PythonContext context) { _context = context; }
public OutputWriter(PythonContext /*!*/ context, bool isErrorOutput) { Assert.NotNull(context); _context = context; _isErrorOutput = isErrorOutput; }