8000 Add PythonEngine.ModuleFromFile() method to load a module from a file. · MITEM/pythonnet@05a1dc6 · GitHub
[go: up one dir, main page]

Skip to content
10000

Commit 05a1dc6

Browse files
committed
Add PythonEngine.ModuleFromFile() method to load a module from a file.
1 parent 19d854c commit 05a1dc6

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/runtime/pythonengine.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,30 @@ public static PyObject ModuleFromString(string name, string code)
422422
return new PyObject(m);
423423
}
424424

425-
public static PyObject Compile(string code, string filename = "", RunFlagType mode = RunFlagType.File)
425+
/// <summary>
426+
/// Load module from a file.
427+
/// </summary>
428+
/// <param name="moduleName">Module name</param>
429+
/// <param name="filePath">Path to the file.</param>
430+
/// <returns>Python module object.</returns>
431+
/// <remarks>
432+
/// <para>In most cases the module name should be the file's base name
433+
/// (Path.GetFileNameWithOutExtension()). However, if you ask for a
434+
/// module that has already been loaded you will get a reference
435+
/// to the existing module. If you want to load code from the file
436+
/// as different modules then create unique module names for each.</para>
437+
/// </remarks>
438+
public static PyObject ModuleFromFile(string moduleName, string filePath)
439+
{
440+
string code = File.ReadAllText(filePath);
441+
IntPtr c = Runtime.Py_CompileString(code, filePath, (IntPtr)257);
442+
Runtime.CheckExceptionOccurred();
443+
IntPtr m = Runtime.PyImport_ExecCodeModule(moduleName, c);
444+
Runtime.CheckExceptionOccurred();
445+
return new PyObject(m);
446+
}
447+
448+
public static PyObject Compile(string code, string filename = "", RunFlagType mode = RunFlagType.File)
426449
{
427450
var flag = (IntPtr)mode;
428451
IntPtr ptr = Runtime.Py_CompileString(code, filename, flag);

0 commit comments

Comments
 (0)
0