From b454f7d0601c9319af533f69c0f509d035fed790 Mon Sep 17 00:00:00 2001 From: Lu Zhen Date: Fri, 9 May 2025 15:50:30 +0800 Subject: [PATCH] fix: python debugpy cannot connect debugpy started but not listen on port, so delay some time to wait it initialized. Log: Bug: https://pms.uniontech.com/bug-view-315851.html Change-Id: I14cd10e5b1fcb63a91b38562f9898f71122fbb67 --- .../debugger/python/pythondebugger.cpp | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/tools/debugadapter/debugger/python/pythondebugger.cpp b/src/tools/debugadapter/debugger/python/pythondebugger.cpp index b27d2f45e..8660a260a 100644 --- a/src/tools/debugadapter/debugger/python/pythondebugger.cpp +++ b/src/tools/debugadapter/debugger/python/pythondebugger.cpp @@ -144,7 +144,30 @@ void PythonDebugger::initialize(const QString &pythonExecute, d->process.setProcessEnvironment(env); d->process.start("/bin/bash", options); d->process.waitForStarted(); - QThread::msleep(500); // The port may not start listening immediately when Python starts, resulting in the IDE being unable to connect. Wait for 500ms. + + // debugpy may not ready when launched,so we should delay when it start listen port. + const int maxRetries = 50; + const int retryInterval = 100; + bool portReady = false; + + for (int i = 0; i < maxRetries && !portReady; i++) { + QProcess checkPort; + QString cmd = QString("netstat -an | grep LISTEN | grep %1").arg(d->port); + checkPort.start("bash", {"-c", cmd}); + checkPort.waitForFinished(); + + if (!checkPort.readAll().isEmpty()) { + portReady = true; + qInfo() << "Debugpy port" << d->port << "is ready after" << (i + 1) * retryInterval << "ms"; + break; + } + + QThread::msleep(retryInterval); + } + + if (!portReady) { + qWarning() << "Debugpy port" << d->port << "failed to start after" << maxRetries * retryInterval << "ms"; + } } void PythonDebugger::slotReceiveClientInfo(const QString &ppid,