X Tutup
Skip to content

Commit 8b8d941

Browse files
committed
Add overload for Initialize to pass specific args.
1 parent ccf9560 commit 8b8d941

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

src/embed_tests/InitializeTest.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,42 @@ namespace Python.EmbeddingTest
99
{
1010
public class InitializeTest
1111
{
12+
[Test]
13+
public static void LoadSpecificArgs()
14+
{
15+
var args = new[] { "test1", "test2" };
16+
PythonEngine.Initialize(args);
17+
try
18+
{
19+
using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv")))
20+
{
21+
Assert.That(argv[0].ToString() == args[0]);
22+
Assert.That(argv[1].ToString() == args[1]);
23+
}
24+
}
25+
finally
26+
{
27+
PythonEngine.Shutdown();
28+
}
29+
}
30+
31+
[Test]
32+
public static void LoadDefaultArgs()
33+
{
34+
PythonEngine.Initialize();
35+
try
36+
{
37+
using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv")))
38+
{
39+
Assert.That(argv.Length() != 0);
40+
}
41+
}
42+
finally
43+
{
44+
PythonEngine.Shutdown();
45+
}
46+
}
47+
1248
[Test]
1349
public static void Test()
1450
{

src/runtime/pythonengine.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
using System.IO;
33
using System.Threading;
44
using System.Reflection;
5+
using System.Collections.Generic;
6+
using System.Linq;
57

68
namespace Python.Runtime
79
{
@@ -102,6 +104,11 @@ public static int RunSimpleString(string code)
102104

103105
#endregion
104106

107+
public static void Initialize()
108+
{
109+
Initialize(Enumerable.Empty<string>());
110+
}
111+
105112
/// <summary>
106113
/// Initialize Method
107114
/// </summary>
@@ -112,7 +119,7 @@ public static int RunSimpleString(string code)
112119
/// first call. It is *not* necessary to hold the Python global
113120
/// interpreter lock (GIL) to call this method.
114121
/// </remarks>
115-
public static void Initialize()
122+
public static void Initialize(IEnumerable<string> args)
116123
{
117124
if (!initialized)
118125
{
@@ -126,6 +133,9 @@ public static void Initialize()
126133
initialized = true;
127134
Exceptions.Clear();
128135

136+
Py.SetArgv(args);
137+
Py.Throw();
138+
129139
// register the atexit callback (this doesn't use Py_AtExit as the C atexit
130140
// callbacks are called after python is fully finalized but the python ones
131141
// are called while the python engine is still running).
@@ -552,9 +562,12 @@ public static void SetArgv(IEnumerable<string> argv)
552562

553563
internal static void Throw()
554564
{
555-
if (Runtime.PyErr_Occurred() != 0)
565+
using (GIL())
556566
{
557-
throw new PythonException();
567+
if (Runtime.PyErr_Occurred() != 0)
568+
{
569+
throw new PythonException();
570+
}
558571
}
559572
}
560573
}

0 commit comments

Comments
 (0)
X Tutup