1import argparse 2 3import gdb 4 5 6class Debugger(gdb.Command): 7 """Start debugpy server or connect to a debug server, so we can debug python code from IDE like PyCharm/VSCode""" 8 9 def __init__(self, host="localhost", port=11451): 10 self.__host = host 11 self.__port = port 12 super().__init__("debugger", gdb.COMMAND_USER) 13 14 def invoke(self, args, from_tty): 15 parser = argparse.ArgumentParser(description=Debugger.__doc__) 16 parser.add_argument( 17 "--host", 18 type=str, 19 help="Server listening host", 20 ) 21 parser.add_argument( 22 "-p", 23 "--port", 24 type=int, 25 help="Server listening port", 26 ) 27 parser.add_argument( 28 "-t", 29 "--type", 30 choices=["pycharm", "vscode", "eclipse"], 31 help="Debugger type", 32 required=True, 33 ) 34 35 try: 36 args = parser.parse_args(gdb.string_to_argv(args)) 37 except SystemExit: 38 return 39 40 if args.host: 41 self.__host = args.host 42 43 if args.port: 44 self.__port = args.port 45 46 if args.type == "pycharm": 47 self.connect_to_pycharm() 48 elif args.type == "vscode": 49 self.connect_to_vscode() 50 elif args.type == "eclipse": 51 self.connect_to_eclipse() 52 53 def connect_to_pycharm(self): 54 try: 55 import pydevd_pycharm 56 except ImportError: 57 print("pydevd_pycharm module not found. Please install it using pip.") 58 return 59 60 pydevd_pycharm.settrace(self.__host, port=self.__port, stdoutToServer=True, stderrToServer=True) 61 62 def connect_to_vscode(self): 63 try: 64 import debugpy 65 except ImportError: 66 print("debugpy module not found. Please install it using pip.") 67 return 68 69 debugpy.listen((self.__host, self.__port)) 70 debugpy.wait_for_client() 71 72 def connect_to_eclipse(self): 73 print("Eclipse is not implemented yet") 74