-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathImport.cs
59 lines (52 loc) · 1.87 KB
/
Import.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.ComponentModel;
using System.IO;
using System.Reactive.Linq;
using Python.Runtime;
using System.Xml.Serialization;
using System.Linq;
namespace Bonsai.Scripting.Python
{
/// <summary>
/// Represents an operator that will import the name of a package as a user-defined named package into the input module.
/// </summary>
[Combinator]
[WorkflowElementCategory(ElementCategory.Transform)]
public class Import
{
[Description("The name of the package.")]
public string Package { get; set; }
[Description("The \"as name\" of the package. For example, in \"import numpy as np\", np is the as name.")]
public string AsName { get; set; }
public IObservable<PyObject> Process(IObservable<PyModule> source)
{
if (string.IsNullOrEmpty(Package))
{
throw new ArgumentException(nameof(Package), "A package must be specified.");
}
return source.Select(module =>
{
using (Py.GIL())
{
if (!string.IsNullOrEmpty(AsName))
{
return module.Import(Package, AsName);
}
if (!Package.Contains('.'))
{
return module.Import(Package);
}
var packages = Package.Split('.');
var packagePath = string.Empty;
PyObject obj = null;
for (int i = 0; i < packages.Length; i++)
{
packagePath = string.IsNullOrEmpty(packagePath) ? packages[i] : $"{packagePath}.{packages[i]}";
obj = module.Import(packagePath);
}
return obj;
}
});
}
}
}