forked from budgetdevv/PythonNETExtensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
111 lines (85 loc) · 3.44 KB
/
Program.cs
File metadata and controls
111 lines (85 loc) · 3.44 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using PythonNETExtensions.Config;
using PythonNETExtensions.Core;
using PythonNETExtensions.Core.Handles;
using PythonNETExtensions.Modules;
using PythonNETExtensions.Modules.BuiltIn;
using PythonNETExtensions.Modules.ThirdParty;
using PythonNETExtensions.Versions;
namespace SampleCode
{
internal static class Program
{
private struct Numpy: IPythonModule<Numpy>
{
public static string DependentPackage => "numpy";
static string IPythonModule<Numpy>.DependentPackageVersion => "2.2.0";
public static string ModuleName => DependentPackage;
}
private static async Task Main(string[] args)
{
var task = Sample();
// Simulate CPU-bound work
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.WriteLine("AsyncIO.Sleep() is non-blocking!");
await task;
}
private static async Task Sample()
{
var pythonCore = new PythonCoreBuilder()
.WithConfig<DefaultPythonConfig>()
.WithVersion<PyVer3_11<DefaultPythonConfig>>()
.Build();
await pythonCore.InitializeAsync();
await pythonCore.InitializeDependentPackages();
using (PythonHandle.Create())
{
const string HELLO_WORLD_TEXT = "Hello World!";
var sys = PythonModule.Get<SysModule>();
var result = RawPython.Run<string>(
$"""
print({HELLO_WORLD_TEXT:py});
return {sys:py}.executable;
""");
Console.WriteLine(result);
var numpy = PythonModule.Get<Numpy>();
Console.WriteLine(numpy.array((int[]) [ 1, 2, 3, 4, 5 ]));
}
using (var handle = AsyncPythonHandle.Create())
{
pythonCore.SetupAsyncIO();
var asyncIO = PythonModule.GetConcrete<AsyncIOModule>();
const int DELAY_SECONDS = 2;
Debug.Assert(DELAY_SECONDS >= 2);
var awaiter = RawPython.RunAsync(
$"""
print("{nameof(asyncIO)} is running!");
await {asyncIO.Sleep(DELAY_SECONDS):py};
""", handle);
await awaiter;
Console.WriteLine($"Hello after {DELAY_SECONDS} seconds");
var threadedTask = Task.Run(() =>
{
using (new PythonHandle())
{
Console.WriteLine("Threaded task running when long-running C# code is");
}
});
LongRunningCSharpCode();
return;
void LongRunningCSharpCode()
{
using (handle.GetLongRunningCSharpRegion())
{
Console.WriteLine("Start of long-running C# code");
Thread.Sleep(1000);
Console.WriteLine("End of long-running C# code");
}
}
}
}
}
}