Skip to content

Instantly share code, notes, and snippets.

@dalmago
Created July 24, 2020 22:31
Show Gist options
  • Save dalmago/85461b066982814fd235a2a8b628fe75 to your computer and use it in GitHub Desktop.
Save dalmago/85461b066982814fd235a2a8b628fe75 to your computer and use it in GitHub Desktop.
Python file used to test debugpy when called from an embedded application
import sys
import os
import time
DEBUG_PORT = 5678
def my_sample_function():
attach_debugger()
print("My code in here")
for i in range(2):
print(i)
time.sleep(1)
print("Put a breakpoint on this line, then press Continue (F5)")
print("The IDE will seem to be paused")
for i in range(10): # do something
# if this sleep is uncommented, then the IDE will get off of the "paused state"
# time.sleep(0.1)
pass
print("End of Python code")
def attach_debugger():
# listen for debugpy client
# waits for 2 minutes. If no connetion is found, proceeds
try:
import debugpy
except ImportError:
print("debugpy is required to run in debug mode.")
print("Please run \"pip install debugpy\" on your Python interpreter")
exit()
# Workaround for: https://github.com/microsoft/debugpy/issues/262
sys_exec = sys.executable
sys.executable = sys.exec_prefix + "\\python.exe"
try:
debugpy.listen(DEBUG_PORT)
print(f"Please attach debugger to port {DEBUG_PORT}")
# blocks execution until debugger is attached
start_time = time.time()
while time.time() - start_time < 120:
if debugpy.is_client_connected():
break
time.sleep(0.1)
if debugpy.is_client_connected():
print("Debugger attached")
else:
print("Timed out.")
print("Will proceed without debugger.")
except RuntimeError:
print("Default port already in use.")
try:
_, port = debugpy.listen(0)
print(f"Please attach debugger to port {port}")
sys.stdout.flush()
# blocks execution until debugger is attached
start_time = time.time()
while time.time() - start_time < 120:
if debugpy.is_client_connected():
break
time.sleep(0.1)
if debugpy.is_client_connected():
print("Debugger attached")
else:
print("Timed out!")
print("Will proceed without debugger.")
except OSError:
print("Could not open any debug port.")
print("Will proceed without debugger.")
finally:
sys.executable = sys_exec
@dalmago
Copy link
Author

dalmago commented Jul 24, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment