StreamFromPythonFile(PythonFile pyFile) { FieldInfo streamField = (FieldInfo)(pyFile.GetType().GetMember( "_stream", BindingFlags.NonPublic | BindingFlags.Instance)[0]); return((FileStream)streamField.GetValue(pyFile)); }
internal static void showwarning(CodeContext context, object message, PythonType category, string filename, int lineno, [DefaultParameterValue(null)] object file, [DefaultParameterValue(null)] string line) { string text = formatwarning(message, category, filename, lineno, line); try { if (file == null) { PythonContext pContext = PythonContext.GetContext(context); PythonFile stderr = pContext.GetSystemStateValue("stderr") as PythonFile; if (stderr != null) { stderr.write(text); } else { // use CLR stderr if python's is unavailable Console.Error.Write(text); } } else { if (file is PythonFile) { ((PythonFile)file).write(text); } else if (file is TextWriter) { ((TextWriter)file).Write(text); } // unrecognized file type - warning is lost } } catch (IOException) { // invalid file - warning is lost } }
public static object Open(ICallerContext context, string filename, int flag, int mode) { FileStream fs = File.Open(filename, FileModeFromFlags(flag), FileAccessFromFlags(flag)); PythonFile pf = PythonFile.Make(context, null, fs); return(PythonFileManager.GetIdFromFile(pf)); }
IC_PyFile_AsFile(IntPtr pyFilePtr) { try { if (this.FILEs.ContainsKey(pyFilePtr)) { return(this.FILEs[pyFilePtr]); } PythonFile pyFile = (PythonFile)this.Retrieve(pyFilePtr); this.PrintToStdErr("Warning: creating unmanaged FILE* from managed stream. Please use ironclad.open with this extension."); int fd = this.ConvertPyFileToDescriptor(pyFile); IntPtr FILE = IntPtr.Zero; if (InappropriateReflection.StreamFromPythonFile(pyFile).CanWrite) { FILE = Unmanaged._fdopen(fd, "w"); } else { FILE = Unmanaged._fdopen(fd, "r"); } this.FILEs[pyFilePtr] = FILE; return(FILE); } catch (Exception e) { this.LastException = e; return(IntPtr.Zero); } }
ConvertPyFileToDescriptor(PythonFile pyFile) { FileStream stream = InappropriateReflection.StreamFromPythonFile(pyFile); SafeHandle safeHandle = stream.SafeFileHandle; IntPtr handle = safeHandle.DangerousGetHandle(); return(Unmanaged._open_osfhandle(handle, 0)); }
/// <summary> /// Get a logger which logs to the console verbose logs /// </summary> /// <param name="file">A python file object to use for output</param> /// <returns>The new logger</returns> public static Logger GetVerboseLogger(PythonFile file) { Logger l = GetLogger(file); l.LogLevel = Logger.LogEntryType.All; return(l); }
/// <summary> /// Get a logger which logs to the console /// </summary> /// <param name="file">A python file object to use for output</param> /// <returns>The new logger</returns> public static Logger GetLogger(PythonFile file) { Logger ret = new Logger(); ret.LogEntryAdded += (sender, e) => ret_LogEntryAdded(file, sender, e); return(ret); }
public static void dump(object value, PythonFile /*!*/ file, int version) { if (file == null) { throw PythonOps.TypeError("expected file, found None"); } file.write(dumps(value, version)); }
public static object load(PythonFile /*!*/ file) { if (file == null) { throw PythonOps.TypeError("expected file, found None"); } return(BytesToObject(FileEnumerator(file))); }
static Analyzer() { state = new SystemState(); PythonFile empty = new PythonFile(System.IO.Stream.Null, System.Text.Encoding.Default, "rw"); state.__stderr__ = empty; state.__stdin__ = empty; state.__stdout__ = empty; }
private static IFile?Parse(FileInfo fileInfo) { IFile?parsedFile = null; switch (fileInfo.Extension) { case ".ps1": case ".bat": case ".sh": case ".cmd": parsedFile = new ShellFile(fileInfo); break; case ".html": case ".md": parsedFile = new DocumentationFile(fileInfo); break; case ".properties": case ".xml": case ".cfg": case ".conf": case ".gitignore": case ".yml": case ".yaml": case ".gradle": case FileExtensions.Json: parsedFile = new ConfigurationFile(fileInfo); break; case ".py": parsedFile = new PythonFile(fileInfo); break; case ".scala": parsedFile = new ScalaFile(fileInfo); break; case FileExtensions.Java: parsedFile = new JavaSourceFile(fileInfo); break; case ".png": default: break; } ; if (parsedFile == null && extensions.Add(fileInfo.FullName)) { Console.WriteLine(fileInfo.FullName); } return(parsedFile); }
private static Stream OpenFile(CodeContext /*!*/ context, PlatformAdaptationLayer pal, string name, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { try { return(pal.OpenInputFileStream(name, fileMode, fileAccess, fileShare)); } catch (UnauthorizedAccessException e) { throw PythonFile.ToIoException(context, name, e); } catch (IOException e) { PythonFile.AddFilename(context, name, e); throw; } }
public static void Dump(object value, object file, object version) { PythonFile pf = file as PythonFile; if (pf == null) { throw Ops.TypeError("expected file, found '{0}'", Ops.GetDynamicType(file).__name__); } pf.Write(DumpString(value, version)); }
public static object Load(object file) { PythonFile pf = file as PythonFile; if (pf == null) { throw Ops.TypeError("expected file, found '{0}'", Ops.GetDynamicType(file).__name__); } return(LoadString(pf.Read())); }
static void ret_LogEntryAdded(PythonFile file, object sender, Logger.LogEntryAddedEventArgs e) { string text = e.LogEntry.Text; if (e.LogEntry.ExceptionObject != null) { text = e.LogEntry.ExceptionObject.ToString(); } file.write(String.Format("[{0}] {1} {2}: {3}\n", e.LogEntry.EntryType, e.LogEntry.Timestamp, e.LogEntry.SourceName, text)); }
private static IEnumerator <byte> FileEnumerator(PythonFile /*!*/ file) { for (; ;) { string data = file.read(1); if (data.Length == 0) { yield break; } yield return((byte)data[0]); } }
StoreTyped(PythonFile obj) { IntPtr ptr = this.allocator.Alloc((uint)Marshal.SizeOf(typeof(PyFileObject))); CPyMarshal.Zero(ptr, Marshal.SizeOf(typeof(PyFileObject))); CPyMarshal.WriteIntField(ptr, typeof(PyObject), "ob_refcnt", 1); CPyMarshal.WritePtrField(ptr, typeof(PyObject), "ob_type", this.PyFile_Type); CPyMarshal.WriteIntField(ptr, typeof(PyFileObject), "f_fp", -2); CPyMarshal.WritePtrField(ptr, typeof(PyFileObject), "f_name", this.Store(obj.name)); CPyMarshal.WritePtrField(ptr, typeof(PyFileObject), "f_mode", this.Store(obj.mode)); this.map.Associate(ptr, obj); return(ptr); }
public static object get_osfhandle(CodeContext context, int fd) { PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd); object handle; if (pfile.TryGetFileHandle(out handle)) { return(handle); } return(-1); }
IC_PyFile_WriteString(string s, IntPtr filePtr) { try { PythonFile file = (PythonFile)this.Retrieve(filePtr); file.write(s); return(0); } catch (Exception e) { this.LastException = e; return(-1); } }
public static object get_osfhandle(CodeContext context, int fd) { PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd); FileStream stream = pfile._stream as FileStream; if (stream != null) { #pragma warning disable 618 // System.IO.FileStream.Handle is obsolete return(stream.Handle.ToPython()); #pragma warning restore 618 } return(-1); }
public static int setmode(CodeContext context, int fd, int flags) { PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd); int oldMode; if (flags == PythonNT.O_TEXT) { oldMode = pfile.SetMode(context, true) ? PythonNT.O_TEXT : PythonNT.O_BINARY; } else if (flags == PythonNT.O_BINARY) { oldMode = pfile.SetMode(context, false) ? PythonNT.O_TEXT : PythonNT.O_BINARY; } else { throw PythonOps.ValueError("unknown mode: {0}", flags); } return(oldMode); }
public static object load_module(CodeContext /*!*/ context, string name, PythonFile file, string filename, PythonTuple /*!*/ description) { if (description == null) { throw PythonOps.TypeError("load_module() argument 4 must be 3-item sequence, not None"); } else if (description.__len__() != 3) { throw PythonOps.TypeError("load_module() argument 4 must be sequence of length 3, not {0}", description.__len__()); } PythonContext pythonContext = PythonContext.GetContext(context); // already loaded? do reload() PythonModule module = pythonContext.GetModuleByName(name); if (module != null) { Importer.ReloadModule(context, module, file); return(module); } int type = PythonContext.GetContext(context).ConvertToInt32(description[2]); switch (type) { case PythonSource: return(LoadPythonSource(pythonContext, name, file, filename)); case CBuiltin: return(LoadBuiltinModule(context, name)); case PackageDirectory: return(LoadPackageDirectory(pythonContext, name, filename)); default: throw PythonOps.TypeError("don't know how to import {0}, (type code {1}", name, type); } }
private static PythonTuple FindModulePath(CodeContext /*!*/ context, string name, List path) { Debug.Assert(path != null); if (name == null) { throw PythonOps.TypeError("find_module() argument 1 must be string, not None"); } PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; foreach (object d in path) { string dir = d as string; if (dir == null) { continue; // skip invalid entries } string pathName = Path.Combine(dir, name); if (pal.DirectoryExists(pathName)) { if (pal.FileExists(Path.Combine(pathName, "__init__.py"))) { return(PythonTuple.MakeTuple(null, pathName, PythonTuple.MakeTuple("", "", PackageDirectory))); } } string fileName = pathName + ".py"; if (pal.FileExists(fileName)) { Stream fs = pal.OpenInputFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PythonFile pf = PythonFile.Create(context, fs, fileName, "U"); return(PythonTuple.MakeTuple(pf, fileName, PythonTuple.MakeTuple(".py", "U", PythonSource))); } } throw PythonOps.ImportError("No module named {0}", name); }
IC_PyFile_WriteObject(IntPtr objPtr, IntPtr filePtr, int use_str) { try { object obj = this.Retrieve(objPtr); string s; if (use_str % 2 == 1) { s = (string)PythonCalls.Call(Builtin.str, new object[] { obj }); } else { s = (string)Builtin.repr(this.scratchContext, obj); } PythonFile file = (PythonFile)this.Retrieve(filePtr); file.write(s); return(0); } catch (Exception e) { this.LastException = e; return(-1); } }
public static object load_dynamic(string name, string pathname, PythonFile file) { return(null); }
private static PythonModule /*!*/ LoadPythonSource(PythonContext /*!*/ context, string /*!*/ name, PythonFile /*!*/ file, string /*!*/ fileName) { SourceUnit sourceUnit = context.CreateSnippet(file.read(), String.IsNullOrEmpty(fileName) ? null : fileName, SourceCodeKind.File); return(context.CompileModule(fileName, name, sourceUnit, ModuleOptions.Initialize)); }
public FileIO(CodeContext /*!*/ context, int fd, [DefaultParameterValue("r")] string mode, [DefaultParameterValue(true)] bool closefd) : base(context) { if (fd < 0) { throw PythonOps.ValueError("fd must be >= 0"); } PythonContext pc = PythonContext.GetContext(context); PythonFile pf = null; FileIO file = null; Stream stream = null; object temp; if (pc.FileManager.TryGetFileFromId(pc, fd, out pf)) { name = (object)pf.name ?? fd; } else if (pc.FileManager.TryGetObjectFromId(pc, fd, out temp)) { file = temp as FileIO; if (file != null) { name = file.name ?? fd; } else { stream = temp as Stream; if (stream != null) { name = fd; } } } _context = pc; switch (StandardizeMode(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; } if (file != null) { _readStream = file._readStream; _writeStream = file._writeStream; } else if (pf != null) { _readStream = pf._stream; _writeStream = pf._stream; } else if (stream != null) { _readStream = stream; _writeStream = stream; } _closefd = closefd; }
public static void dump(object value, PythonFile /*!*/ file) { dump(value, file, version); }
public static object GetFileFStats(int fd) { PythonFile pf = PythonFileManager.GetFileFromId(fd); return(GetFileStats(pf.name)); }
public static object load_source(CodeContext /*!*/ context, string /*!*/ name, string /*!*/ pathname, PythonFile /*!*/ file) { if (name == null) { throw PythonOps.TypeError("load_source() argument 1 must be string, not None"); } if (pathname == null) { throw PythonOps.TypeError("load_source() argument 2 must be string, not None"); } if (file == null) { throw PythonOps.TypeError("load_source() argument 3 must be file, not None"); } return(LoadPythonSource(PythonContext.GetContext(context), name, file, pathname)); }