18 using System.Threading;
19 using System.Diagnostics;
23 using System.Collections.Concurrent;
32 private static readonly ConcurrentQueue<Py.GILState> _threadsState =
new();
81 workersInitializationCallback =
null;
87 Log.
Trace(
"DebuggerHelper.Initialize(): initializing python...");
89 Log.
Trace(
"DebuggerHelper.Initialize(): python initialization done");
93 Log.
Trace(
"DebuggerHelper.Initialize(): starting...");
94 switch (debuggingType)
97 PythonEngine.RunSimpleString(
"import pdb; pdb.set_trace()");
101 Log.
Trace(
"DebuggerHelper.Initialize(): waiting for debugger to attach...");
102 PythonEngine.RunSimpleString(
@"import sys; import time;
103 while not sys.gettrace():
108 Log.
Trace(
"DebuggerHelper.Initialize(): waiting for PTVSD debugger to attach at localhost:5678...");
109 PythonEngine.RunSimpleString(
"import ptvsd; ptvsd.enable_attach(); ptvsd.wait_for_attach()");
113 PythonEngine.RunSimpleString(
@"import debugpy
114 from AlgorithmImports import *
115 from QuantConnect.Logging import *
117 Log.Trace(""DebuggerHelper.Initialize(): debugpy waiting for attach at port 5678..."");
119 debugpy.listen(('0.0.0.0', 5678))
120 debugpy.wait_for_client()");
121 workersInitializationCallback = DebugpyThreadInitialization;
125 Log.
Trace(
"DebuggerHelper.Initialize(): Attempting to connect to Pycharm PyDev debugger server...");
126 PythonEngine.RunSimpleString(
@"import pydevd_pycharm; import time;
130 pydevd_pycharm.settrace('localhost', port=6000, stdoutToServer=True, stderrToServer=True, suspend=False)
131 print('SUCCESS: Connected to local program')
133 except ConnectionRefusedError:
137 pydevd_pycharm.settrace('host.docker.internal', port=6000, stdoutToServer=True, stderrToServer=True, suspend=False)
138 print('SUCCESS: Connected to docker container')
140 except ConnectionRefusedError:
144 print('Failed: Ensure your PyCharm Debugger is actively waiting for a connection at port 6000!')
145 print('Try ' + count.__str__() + ' out of 10')
151 Log.
Trace(
"DebuggerHelper.Initialize(): started");
154 else if(language ==
Language.CSharp)
156 if (Debugger.IsAttached)
158 Log.
Trace(
"DebuggerHelper.Initialize(): debugger is already attached, triggering initial break.");
162 Log.
Trace(
"DebuggerHelper.Initialize(): waiting for debugger to attach...");
163 while (!Debugger.IsAttached)
167 Log.
Trace(
"DebuggerHelper.Initialize(): debugger attached");
172 throw new NotImplementedException($
"DebuggerHelper.Initialize(): not implemented for {language}");
181 private static void DebugpyThreadInitialization()
183 _threadsState.Enqueue(Py.GIL());
184 PythonEngine.BeginAllowThreads();
186 Log.
Debug($
"DebuggerHelper.Initialize({Thread.CurrentThread.Name}): initializing debugpy for thread...");
189 PythonEngine.RunSimpleString(
"import debugpy;debugpy.debug_this_thread();debugpy.trace_this_thread(True)");