private static void doPython(string FiletoScan, ref XMLParser raport) { var engine = Python.CreateEngine(); var searchPaths = engine.GetSearchPaths(); searchPaths.Add(@"C:\Python27\Lib"); engine.SetSearchPaths(searchPaths); List <String> argv = new List <String>(); argv.Add(FiletoScan); engine.GetSysModule().SetVariable("argv", argv); // podanie argumentów do skryptu var scope = engine.ExecuteFile(AppDomain.CurrentDomain.BaseDirectory + "pdfid.py"); dynamic pdfid = scope.GetVariable("PDFiD"); var xml = pdfid(FiletoScan); // otrzymanie xml z metody pdfid dynamic cPDFiD = scope.GetVariable("cPDFiD"); //klasa cPDFiD dynamic cpdf = cPDFiD(xml, true); //objekt klasy cPDFiF IronPython.Runtime.PythonDictionary d = cpdf.keywords; //słownik z wynikami raport.InitializePDFInfo(); foreach (string key in cpdf.keywords) { raport.AddPDFInfoAtt(key, d.get(key).ToString()); } }
private void SetRamulatorWordState(bool state, IronPython.Runtime.PythonDictionary wordData) { Dictionary <string, object> dotNetWordData = new Dictionary <string, object>(); foreach (string key in wordData.Keys) { dotNetWordData.Add(key, wordData[key] == null ? "" : wordData[key].ToString()); } SetRamulatorState("WORD", state, dotNetWordData); }
private void WriteLstFile(string lstFilePath) { string[] lines = new string[settings.wordsPerList]; int startIndex = wordsSeen - settings.wordsPerList; for (int i = startIndex; i < wordsSeen; i++) { IronPython.Runtime.PythonDictionary word = words[i]; lines[i - (startIndex)] = (string)word["word"]; } System.IO.FileInfo lstFile = new System.IO.FileInfo(lstFilePath); lstFile.Directory.Create(); WriteAllLinesNoExtraNewline(lstFile.FullName, lines); }
protected IronPython.Runtime.List ReadWordsFromPoolTxt(string path, bool isCategoryPool) { string[] lines = GetWordpoolLines(path); IronPython.Runtime.List words = new IronPython.Runtime.List(); for (int i = 0; i < lines.Length; i++) { IronPython.Runtime.PythonDictionary word = new IronPython.Runtime.PythonDictionary(); if (isCategoryPool) { string line = lines[i]; string[] category_and_word = line.Split('\t'); word["category"] = category_and_word[0]; word["word"] = category_and_word[1]; } else { word["word"] = lines[i]; } words.Add(word); } return(words); }
/// <summary> /// 用于测试 /// </summary> /// <returns></returns> public static ArrayList test() { ArrayList returnList = new ArrayList(); string serverpath = "D:\\projects\\recommandSystem\\UserCFRecommend.py"; ScriptRuntime pyRuntime = Python.CreateRuntime(); ScriptEngine Engine = pyRuntime.GetEngine("python"); ICollection <string> Paths = Engine.GetSearchPaths(); Paths.Add("D:\\Anaconda2-32\\Lib"); Paths.Add("D:\\Anaconda2-32\\DLLs"); Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages"); ScriptScope pyScope = Engine.CreateScope(); //Engine.ImportModule("pandas"); //Engine.ImportModule("math"); //Engine.ImportModule("pickle"); Engine.SetSearchPaths(Paths); IronPython.Runtime.PythonDictionary pyDic = new IronPython.Runtime.PythonDictionary(); ArrayList A = new ArrayList(); A.Add('a'); A.Add('b'); A.Add('d'); ArrayList B = new ArrayList(); B.Add('a'); B.Add('c'); ArrayList C = new ArrayList(); C.Add('b'); C.Add('e'); ArrayList D = new ArrayList(); D.Add('c'); D.Add('d'); D.Add('e'); pyDic.Add('A', A); pyDic.Add('B', B); pyDic.Add('C', C); pyDic.Add('D', D); dynamic obj = Engine.ExecuteFile(serverpath, pyScope); IronPython.Runtime.List result = obj.recommmend_user_cf('A', pyDic, 3); for (int i = 0; i < result.Count; i++) { IronPython.Runtime.PythonTuple pySet = (IronPython.Runtime.PythonTuple)result.ElementAt(i); Console.WriteLine(pySet.ElementAt(0)); Console.WriteLine(pySet.ElementAt(1)); returnList.Add(pySet.ElementAt(0)); } Console.WriteLine(result); return(returnList); }
/// <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 (context.LanguageContext.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 (context.LanguageContext.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); }
public SimpleNamespace([ParamDictionary, NotNull] Dictionary <string, object?> kwargs\u00F8) { __dict__ = new PythonDictionary(kwargsø); }
private static int _CurrentId = 1; // The current ID for functions which are called in complex ways. /// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { throw new NotImplementedException(); }
/// <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); } 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 // 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 if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod)) { newmod = ImportFromPath(context, firstName, name, path); if (newmod == null) { // 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) { parentModule.__dict__[firstName] = 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. if (newmod is NamespaceTracker) { context.ShowCls = true; } } } } if (level <= 0) { // try an absolute import if (newmod == null) { object parentPkg; if (!String.IsNullOrEmpty(package) && !context.LanguageContext.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); } 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); }
private static PythonDictionary MakeDictFromIAC(CodeContext context, PythonDictionary iac) { return(new PythonDictionary(new ObjectAttributesAdapter(context, iac))); }
internal static PythonDictionary FromIAC(CodeContext context, PythonDictionary iac) { return(iac.GetType() == typeof(PythonDictionary) ? (PythonDictionary)iac : MakeDictFromIAC(context, iac)); }
internal PythonDictionary(PythonDictionary dict) { _storage = dict._storage.Clone(); }
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); }
public DebugProxy(PythonDictionary dict) { _dict = dict; }