| | | 1 | | using Elsa.Expressions.Python.Options; |
| | | 2 | | using Microsoft.Extensions.Hosting; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using Python.Runtime; |
| | | 6 | | |
| | | 7 | | namespace Elsa.Expressions.Python.HostedServices; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Initializes the Python engine. |
| | | 11 | | /// </summary> |
| | | 12 | | public class PythonGlobalInterpreterManager : IHostedService |
| | | 13 | | { |
| | | 14 | | private readonly IOptions<PythonOptions> _options; |
| | | 15 | | private readonly ILogger _logger; |
| | | 16 | | private IntPtr _mainThreadState; |
| | | 17 | | private static bool _initialized; |
| | | 18 | | |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Initializes a new instance of the <see cref="PythonGlobalInterpreterManager"/> class. |
| | | 22 | | /// </summary> |
| | 1 | 23 | | public PythonGlobalInterpreterManager(IOptions<PythonOptions> options, ILogger<PythonGlobalInterpreterManager> logge |
| | | 24 | | { |
| | 1 | 25 | | _options = options; |
| | 1 | 26 | | _logger = logger; |
| | 1 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | | 30 | | public Task StartAsync(CancellationToken cancellationToken) |
| | | 31 | | { |
| | 1 | 32 | | if (_initialized) |
| | 0 | 33 | | return Task.CompletedTask; |
| | | 34 | | |
| | 1 | 35 | | if (!string.IsNullOrEmpty(_options.Value.PythonDllPath)) |
| | 0 | 36 | | Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", _options.Value.PythonDllPath); |
| | | 37 | | |
| | | 38 | | try |
| | | 39 | | { |
| | 1 | 40 | | PythonEngine.Initialize(); |
| | 0 | 41 | | _mainThreadState = PythonEngine.BeginAllowThreads(); |
| | 0 | 42 | | } |
| | 1 | 43 | | catch (Exception e) |
| | | 44 | | { |
| | 1 | 45 | | _logger.LogWarning(e, "Failed to initialize Python engine"); |
| | 1 | 46 | | } |
| | | 47 | | |
| | 1 | 48 | | _initialized = true; |
| | 1 | 49 | | return Task.CompletedTask; |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | /// <inheritdoc /> |
| | 2 | 53 | | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; |
| | | 54 | | } |