8000 add a scope class to manage the context of interaction with Python an… · pythonnet/pythonnet@c65d1d0 · GitHub
[go: up one dir, main page]

Skip to content

Commit c65d1d0

Browse files
committed
add a scope class to manage the context of interaction with Python and simplify the variable exchanging
1 parent 1d583c7 commit c65d1d0

File tree

3 files changed

+447
-0
lines changed

3 files changed

+447
-0
lines changed

src/embed_tests/Python.EmbeddingTest.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
<Compile Include="pyobject.cs" />
8585
<Compile Include="pythonexception.cs" />
8686
<Compile Include="pytuple.cs" />
87+
<Compile Include="pyscope.cs" />
8788
</ItemGroup>
8889
<ItemGroup>
8990
<ProjectReference Include="..\runtime\Python.Runtime.csproj">

src/embed_tests/pyscope.cs

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
using NUnit.Framework;
2+
using Python.Runtime;
3+
4+
namespace Python.EmbeddingTest
5+
{
6+
[TestFixture]
7+
public class PyScopeTest
8+
{
9+
PyScope session;
10+
PyScope ps;
11+
12+
public PyScopeTest()
13+
{
14+
session = Py.Session();
15+
}
16+
17+
[SetUp]
18+
public void SetUp()
19+
{
20+
ps = session.Scope();
21+
}
22+
23+
[TearDown]
24+
public void TearDown()
25+
{
26+
ps.Dispos 8000 e();
27+
}
28+
29+
/// <summary>
30+
/// Evaluation a Python expression and obtain the value.
31+
/// </summary>
32+
[Test]
33+
public void TestEval()
34+
{
35+
ps.SetLocal("a", 1);
36+
PyInt result = PyInt.AsInt(ps.Eval("a+2"));
37+
Assert.AreEqual(result.ToInt32(), 3);
38+
}
39+
40+
[Test]
41+
public void TestExec()
42+
{
43+
ps.SetGlobal("bb", 100); //declare a global variable
44+
ps.SetLocal("cc", 10); //declare a local variable
45+
ps.Exec("aa=bb+cc+3");
46+
int result = ps.Get<System.Int32>("aa");
47+
Assert.AreEqual(result, 113);
48+
}
49+
50+
[Test]
51+
public void TestExecIn()
52+
{
53+
ps.SetGlobal("bb", 100); //declare a global variable
54+
ps.SetLocal("cc", 10); //declare a local variable
55+
ps.ExecIn("aa=bb+cc+3");
56+
PyInt result = PyInt.AsInt(ps.Get("aa") as PyObject);
57+
Assert.AreEqual(result.ToInt32(), 113);
58+
}
59+
60+
[Test]
61+
public void TestImport()
62+
{
63+
ps.SetGlobal("bb", 100); //declare a global variable
64+
ps.SetLocal("cc", 10); //declare a local variable
65+
ps.ExecIn("aa=bb+cc+3");
66+
PyInt result = PyInt.AsInt(ps.Get("aa") as PyObject);
67+
Assert.AreEqual(result.ToInt32(), 113);
68+
}
69+
70+
[Test]
71+
public void TestSuspend()
72+
{
73+
var ps = Py.Session();
74+
ps.SetGlobal("bb", 100);
75+
ps.SetLocal("cc", 10);
76+
ps.Suspend();
77+
using (Py.GIL())
78+
{
79+
PythonEngine.RunSimpleString("import sys;");
80+
}
81+
ps.ExecIn("aa=bb+cc+3");
82+
int result = ps.Get<System.Int32>("aa");
83+
Assert.AreEqual(result, 113);
84+
}
85+
}
86+
}

0 commit comments

Comments
 (0)
0