def notify(self, args): try: input = json.loads(args.additionalInfo) script_path = os.path.abspath(input['script']) detach = input['detach'] if os.path.isfile(script_path): script_name = os.path.splitext( os.path.basename(script_path))[0] script_dir = os.path.dirname(script_path) sys.path.append(script_dir) try: module = importlib.import_module(script_name) importlib.reload(module) module.run(saved_context) finally: del sys.path[-1] if detach: try: import pydevd pydevd.stoptrace() except: pass except: traceback.print_exc() if ui: ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
async def debug(self, engine, options): """ Setup middlewared for remote debugging. engines: - PTVS: Python Visual Studio - PYDEV: Python Dev (Eclipse/PyCharm) options: - secret: password for PTVS - host: required for PYDEV, hostname of local computer (developer workstation) - local_path: required for PYDEV, path for middlewared source in local computer (e.g. /home/user/freenas/src/middlewared/middlewared """ if engine == 'PTVS': import ptvsd if 'secret' not in options: raise ValidationError('secret', 'secret is required for PTVS') ptvsd.enable_attach( options['secret'], address=(options['bind_address'], options['bind_port']), ) if options['wait_attach']: ptvsd.wait_for_attach() elif engine == 'PYDEV': for i in ('host', 'local_path'): if i not in options: raise ValidationError(i, f'{i} is required for PYDEV') os.environ['PATHS_FROM_ECLIPSE_TO_PYTHON'] = json.dumps([ [options['local_path'], '/usr/local/lib/python3.6/site-packages/middlewared'], ]) import pydevd pydevd.stoptrace() pydevd.settrace(host=options['host'])
async def debug_start(call: Optional[ServiceCall] = None) -> None: """Start the debugger.""" _LOGGER.info(f"Activating PyCharm Remote Debugger for {host}:{port}") debugger = get_global_debugger() if debugger: _LOGGER.warning(f"Found running PyDB instance, stopping it now") _LOGGER.debug(f"connected={connected}") stoptrace() while connected: await asyncio.sleep(0.1) # DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 try: pydevd_pycharm.settrace( host=host, port=port, stdoutToServer=False, stderrToServer=False, suspend=wait, trace_only_current_thread=False, patch_multiprocessing=False, ) except (ConnectionRefusedError, OSError, socket.gaierror) as e: _LOGGER.warning( "Failed to connect Remote Debugger with PyCharm IDE")
def execute(self, context): user_preferences = context.user_preferences addon_prefs = user_preferences.addons[__name__].preferences sys.path.append(addon_prefs.pydevd_dir) import pydevd pydevd.stoptrace() return{'FINISHED'}
def notify(self, args): try: args = json.loads(args.additionalInfo) script_path = os.path.abspath(args['script']) detach = args['detach'] if os.path.isfile(script_path): script_name = os.path.splitext( os.path.basename(script_path))[0] script_dir = os.path.dirname(script_path) sys.path.append(script_dir) try: import attach_script attach_script.attach(args['debug_port'], 'localhost') module = importlib.import_module(script_name) importlib.reload(module) module.run({'isApplicationStartup': False}) finally: del sys.path[-1] if detach: try: import pydevd pydevd.stoptrace() except: pass except: with open(script_run_log_path, 'w') as f: f.write(traceback.format_exc())
def decorated(request, *args, **kwargs): debug_server = request['args'].get(SECRET_DEBUG_KEYWORD, False) if debug_server: import pydevd import socket hostname, port = debug_server.split(":") port = int(port) try: # we cannot check if port is open since otherwise # setting the wrong hostname:port will trigger an irrecoverable system exit, because : # We cannot monkey patch due to pydevd already heavily monkey patching # from _pydevd_bundle import pydevd_comm # pydevd_comm.start_client = start_client... # And this makes weird and undefined behaviour: # s = socket.socket() # s.settimeout(0.5) # s.connect((hostname, port)) # s.close() pydevd.settrace(host=hostname, stdoutToServer=True, stderrToServer=True, port=int(port)) except Exception: raise UserException(DEBUG_SERVER_CONNECTION_FAILURE) try: result = wrapped(request, *args, **kwargs) finally: if debug_server: pydevd.stoptrace() return result
def toggle_remote_debug(): """ for remote debug usage only NOTE: Using jetbrains' python remote debug util for remote debug, please copy pycharm-debug-py3k.egg to the root of project. For complete remote debugging steps, please refer to pycharm's remote debugging documentation. Then start shell with `pysh.py --remote-debug`, `--remote-debug must be first argument` :return: """ import sys import os debug_on = len(sys.argv) >= 2 and '--remote-debug' in sys.argv[1] if debug_on: egg_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "pycharm-debug-py3k.egg")) sys.path.append(egg_path) import pydevd pydevd.settrace('localhost', port=9090) yield if debug_on: import pydevd pydevd.stoptrace()
def __debug(self, engine, options): if engine == 'PTVS': import ptvsd if 'secret' not in options: raise ValidationError('secret', 'secret is required for PTVS') ptvsd.enable_attach( options['secret'], address=(options['bind_address'], options['bind_port']), ) if options['wait_attach']: ptvsd.wait_for_attach() elif engine == 'PYDEV': for i in ('host', 'local_path'): if i not in options: raise ValidationError(i, f'{i} is required for PYDEV') os.environ['PATHS_FROM_ECLIPSE_TO_PYTHON'] = json.dumps([ [ options['local_path'], '/usr/local/lib/python3.7/site-packages/middlewared' ], ]) import pydevd pydevd.stoptrace() pydevd.settrace(host=options['host']) elif engine == 'REMOTE_PDB': from remote_pdb import RemotePdb RemotePdb(options['bind_address'], options['bind_port']).set_trace()
def main(): try: try: import maya.cmds as cmds import maya.utils if not cmds.commandPort(':{}'.format(PORT), q=1): cmds.commandPort(n=':{}'.format(PORT)) # maya.utils.executeDeferred(cmds.commandPort(n=':{}'.format(PORT))) print(cmds.commandPort(':{}'.format(PORT), q=1)) except ImportError: import hou, hrpyc hrpyc.start_server(PORT, False, False) pydevd.stoptrace() pydevd.settrace("localhost", port=PORT - 1, stdoutToServer=True, stderrToServer=True) print("trace start") except: pydevd.stoptrace() cmds.commandPort(n=':{}'.format(PORT), close=1) print("trace stop", "maya port {}".format(cmds.commandPort(':{}'.format(PORT), q=1)))
def bootstrap_random_trailers(screensaver: bool) -> None: """ :param screensaver: True when launched as a screensaver :return: """ try: Monitor.register_settings_changed_listener( Settings.on_settings_changed) Monitor.register_settings_changed_listener( LazyLogger.on_settings_changed) MainThreadLoop.class_init(screensaver) MainThreadLoop.startup() # LazyLogger can be unusable during shutdown if module_logger.isEnabledFor(LazyLogger.DEBUG): module_logger.exit('Exiting plugin') except AbortException: pass # Exit in finally block except Exception: module_logger.exception('') finally: if REMOTE_DEBUG: try: pydevd.stoptrace() except Exception: pass sys.exit(0)
async def debug(self, engine, options): """ Setup middlewared for remote debugging. engines: - PTVS: Python Visual Studio - PYDEV: Python Dev (Eclipse/PyCharm) options: - secret: password for PTVS - host: required for PYDEV, hostname of local computer (developer workstation) - local_path: required for PYDEV, path for middlewared source in local computer (e.g. /home/user/freenas/src/middlewared/middlewared """ if engine == 'PTVS': import ptvsd if 'secret' not in options: raise ValidationError('secret', 'secret is required for PTVS') ptvsd.enable_attach( options['secret'], address=(options['bind_address'], options['bind_port']), ) if options['wait_attach']: ptvsd.wait_for_attach() elif engine == 'PYDEV': for i in ('host', 'local_path'): if i not in options: raise ValidationError(i, f'{i} is required for PYDEV') os.environ['PATHS_FROM_ECLIPSE_TO_PYTHON'] = json.dumps([ [options['local_path'], '/usr/local/lib/python3.7/site-packages/middlewared'], ]) import pydevd pydevd.stoptrace() pydevd.settrace(host=options['host'])
def killDebugThreads(self): ''' This kills all PyDevd Remote Debugger Threads ''' try: self.updatePath() import pydevd pydevd.stoptrace() except: pass pass
def killDebugThreads(self): ''' This kills all PyDevd Remote Debugger Threads ''' try: # self.updatePath() import pydevd pydevd.stoptrace() log.debug("pydevd Debugger Threads stopped") except: pass
def main(self): if len(sys.argv) != 2: print("Invalid number of arguments", file=sys.stderr) sys.exit(errno.EINVAL) key = sys.argv[1] logging.basicConfig(level=logging.DEBUG) self.datastore = get_default_datastore() self.configstore = ConfigStore(self.datastore) self.conn = Client() self.conn.connect('unix:') self.conn.login_service('task.{0}'.format(os.getpid())) self.conn.enable_server() self.conn.rpc.register_service_instance('taskproxy', self.service) self.conn.call_sync('task.checkin', key) setproctitle.setproctitle('task executor (idle)') while True: try: task = self.task.get() setproctitle.setproctitle('task executor (tid {0})'.format(task['id'])) if task['debugger']: sys.path.append('/usr/local/lib/dispatcher/pydev') import pydevd host, port = task['debugger'] pydevd.settrace(host, port=port, stdoutToServer=True, stderrToServer=True) module = imp.load_source('plugin', task['filename']) setproctitle.setproctitle('task executor (tid {0})'.format(task['id'])) try: self.instance = getattr(module, task['class'])(DispatcherWrapper(self.conn), self.datastore) self.instance.configstore = self.configstore self.running.set() result = self.instance.run(*task['args']) except BaseException as err: print("Task exception: {0}".format(str(err)), file=sys.stderr) traceback.print_exc(file=sys.stderr) self.put_status('FAILED', exception=err) else: self.put_status('FINISHED', result=result) except RpcException as err: print("RPC failed: {0}".format(str(err)), file=sys.stderr) sys.exit(errno.EBADMSG) except socket.error as err: print("Cannot connect to dispatcher: {0}".format(str(err)), file=sys.stderr) sys.exit(errno.ETIMEDOUT) if task['debugger']: import pydevd pydevd.stoptrace() setproctitle.setproctitle('task executor (idle)')
def stop_pycharm_debug(self): try: if self.pycharm_debug and ( not os.path.isfile(PYCHARM_DEBUG_CONFIG)): pydevd.stoptrace() self.pycharm_debug = False except Exception as e: _logger.error( r'XDebugHelper stop_pycharm_debug Exception : {}'.format(e), exc_info=True)
def clean_exit(): print 'Main thread termination' try: if pydevd.GetGlobalDebugger() is not None: print '#################################################' print '######## Remote debug session ended ##########' print '#################################################' pydevd.stoptrace() except: pass
def killDebugThreads(): ''' This kills all PyDevd Remote Debugger Threads ''' if DEBUG_ENABLED: try: updatePath() import pydevd pydevd.stoptrace() except: pass pass
def wrapper(*args, **kwargs): import pydevd pydevd.settrace('localhost', port=4242, stdoutToServer=True, stderrToServer=True) try: func(*args, **kwargs) except Exception as e: pydevd.stoptrace() raise pydevd.stoptrace()
def stopPyDevD(): global bwPyDevDStarted if bwPyDevDStarted: bwPyDevDStarted = False try: import pydevd pydevd.stoptrace() del threading.currentThread().__pydevd_id__ bwdebug.INFO_MSG('PyDevD debug has stopped') except Exception as e: from traceback import print_exc print_exc() bwdebug.ERROR_MSG('Failed to stop pydevd: %s' % repr(e))
def ui_thread_runner(cls): try: cls._start_ui = random_trailers_ui.StartUI(cls._is_screensaver) cls._start_ui.start() except AbortException: if REMOTE_DEBUG: try: pydevd.stoptrace() except Exception: pass pass # Thread to die except Exception: cls._logger.exception('')
def attach(port, host, protocol=''): try: import sys fix_main_thread = 'threading' not in sys.modules if fix_main_thread: def on_warn(msg): from _pydev_bundle import pydev_log pydev_log.warn(msg) def on_exception(msg): from _pydev_bundle import pydev_log pydev_log.exception(msg) def on_critical(msg): from _pydev_bundle import pydev_log pydev_log.critical(msg) fix_main_thread_id(on_warn=on_warn, on_exception=on_exception, on_critical=on_critical) else: from _pydev_bundle import pydev_log # @Reimport pydev_log.debug( 'The threading module is already imported by user code.') if protocol: from _pydevd_bundle import pydevd_defaults pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol import pydevd pydevd.stoptrace() # I.e.: disconnect if already connected # pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 pydevd.settrace( port=port, host=host, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) except: import traceback traceback.print_exc()
def attach_to_pycharm(*args): """Attach the the PyCharm remote debugger""" import pydevd # disconnect if already connected pydevd.stoptrace() # (re)connect pydevd.settrace('localhost', suspend=False, port=5000, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True)
def stopListening(): global isListening if not isListening: return True try: import pydevd pydevd.stoptrace() isListening = False print("[PythonDebug] Debug server stopped") return True except Exception as error: print("[PythonDebug] Failed to stop debug server %s" % error) return False
def attach(port, host): try: import pydevd pydevd.stoptrace() #I.e.: disconnect if already connected # pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 pydevd.settrace( port=port, host=host, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) except: import traceback;traceback.print_exc()
def attach(port, host): try: import pydevd pydevd.stoptrace() # I.e.: disconnect if already connected pydevd.settrace( port=port, host=host, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) print("successfully attached to maya") except: import traceback traceback.print_exc()
def connect_debugger(reconnect=False): # hostname host.docker.internal is only available on MacOs and Windows (not Linux atm) docker_host_ip = socket.gethostbyname('host.docker.internal') log.debug(f'Docker Host IP: {docker_host_ip} ') pydevd_port = int(os.environ.get('CSD_WEBAPP_PYDEVD_PORT', 4444)) try: if reconnect: pydevd.stoptrace() pydevd.settrace( docker_host_ip, port=pydevd_port, stdoutToServer=True, stderrToServer=True, suspend=False, ) except ConnectionRefusedError as e: # log.exception(f'pydev connection refused for {docker_host_ip}:{pydevd_port}') raise
def attach(port, host): try: import pydevd pydevd.stoptrace() #I.e.: disconnect if already connected # pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 pydevd.settrace( port=port, host=host, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) except: import traceback;traceback.print_exc()
def event_processing_loop(cls) -> None: """ :return: """ try: # For the first 10 seconds use a short timeout so that initialization # stuff is handled quickly. Then revert to 0.10 seconds initial_timeout = 0.05 switch_timeouts_count = 10 * 20 i = 0 timeout = initial_timeout # Using _wait_for_abort to # cause Monitor to query Kodi for Abort on the main thread. # If this is not done, then Kodi will get constipated # sending/receiving events to plugins. while not Monitor._wait_for_abort(timeout=timeout): i += 1 if i == switch_timeouts_count: timeout = 0.10 try: task = cls._callableTasks.get(block=False) cls.run_task(task) except queue.Empty: pass Monitor.throw_exception_if_abort_requested(timeout=timeout) except AbortException: if REMOTE_DEBUG: try: pydevd.stoptrace() except Exception: pass reraise(*sys.exc_info()) except Exception as e: cls._logger.exception(e)
def connect_to_debugger(): """ If you want to debug your code via PyCharm: 1. Click "Debug" 2. Run this ONCE early on in any code that you run from within the Maya python tab. Based on https://matiascodesal.com/blog/how-to-use-pycharms-remote-debugging-with-maya/ """ # This should be the path your PyCharm installation if PYDEVD_EGG not in sys.path: sys.path.append(PYDEVD_EGG) # This clears out any previous connection in case you restarted the debugger from PyCharm pydevd.stoptrace() # 9001 matches the port number that I specified in my configuration pydevd_pycharm.settrace('localhost', port=9001, stdoutToServer=True, stderrToServer=True, suspend=False)
def bootstrap_random_trailers(): # type: () -> None """ First function called at startup. Note this means that this is running on the main thread :return: """ try: if MainThreadLoop.profiler is not None: MainThreadLoop.profiler.enable() thread = threading.Thread( target=profiler_thread, name='back_end_service.profiler_thread') thread.start() main_loop = MainThreadLoop.get_instance() try: thread = threading.Thread( target=startup_non_main_thread, name='back_end_service.startup_main_thread') thread.start() except Exception: module_logger.exception('') main_loop.event_processing_loop() except AbortException as e: pass except Exception as e: module_logger.exception('') finally: if REMOTE_DEBUG: try: pydevd.stoptrace() except Exception: pass sys.exit(0)
def readSettings(self): '''(Re-)read all settings''' misc.log('Reading settings') addon = xbmcaddon.Addon() self.enable = addon.getSetting('hyperion_enable') == 'true' self.enableScreensaver = addon.getSetting( 'screensaver_enable') == 'true' self.address = addon.getSetting('hyperion_host') self.port = int(addon.getSetting('hyperion_port')) self.priority = int(addon.getSetting('hyperion_priority')) self.timeout = int(addon.getSetting('reconnect_timeout')) self.capture_width = int(addon.getSetting('capture_width')) self.capture_height = int(addon.getSetting('capture_height')) self.framerate = int(addon.getSetting('framerate')) self.debug = addon.getSetting('debug') == 'true' self.debug_host = addon.getSetting('debug_host') self.debug_port = int(addon.getSetting('debug_port')) self.showErrorMessage = True self.rev += 1 if self.debug: try: import pydevd pydevd.settrace(host=settings.debug_host, port=settings.debug_port, stdoutToServer=True, stderrToServer=True) self._debugging = True except Exception as exception: misc.notify('Error while enabling debugger: %(exception)r', exception=exception) elif self._debugging: import pydevd pydevd.stoptrace() self._debugging = False
def attach(port, host, protocol=''): try: if protocol: from _pydevd_bundle import pydevd_defaults pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol import pydevd pydevd.stoptrace() # I.e.: disconnect if already connected # pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True # pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3 # pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3 pydevd.settrace( port=port, host=host, stdoutToServer=True, stderrToServer=True, overwrite_prev_trace=True, suspend=False, trace_only_current_thread=False, patch_multiprocessing=False, ) except: import traceback traceback.print_exc()
print "Searching for EFI protocols..." tools.update_protocols() print "Updating structures from xrefs..." tools.update_structs_from_xrefs() print "Searching for EFI protocols..." tools.update_protocols() print "Updating structures from lvars..." for protocol in filter(lambda x: x.interface is not None, protocols): if isinstance(protocol.interface.storage, StructureMember): start = protocol.introduced_at lvar = protocol.interface.storage struc = protocol.struc print "Working on %s %s at 0x%X" % (struc, lvar, start) tools.update_struct_from_lvar(start, lvar, struc) for protocol in protocols: print protocol.name print " GUID : %s" % protocol.guid.as_uuid() print " Interface : %s" % protocol.interface print " Introduced at : 0x%X" % protocol.introduced_at print " Class : %s" % str(protocol.__class__).split(".")[-1] print "Finished in %f seconds" % (time.time() - start) print "pydevd.stoptrace()" pydevd.stoptrace()
def debug_stop(): try: import pydevd pydevd.stoptrace() except: pass
def main(self): if len(sys.argv) != 2: print("Invalid number of arguments", file=sys.stderr) sys.exit(errno.EINVAL) key = sys.argv[1] configure_logging(None, logging.DEBUG) self.datastore = get_datastore() self.configstore = ConfigStore(self.datastore) self.conn = Client() self.conn.connect('unix:') self.conn.login_service('task.{0}'.format(os.getpid())) self.conn.enable_server() self.conn.rpc.register_service_instance('taskproxy', self.service) self.conn.register_event_handler('task.progress', self.task_progress_handler) self.conn.call_sync('task.checkin', key) setproctitle.setproctitle('task executor (idle)') while True: try: task = self.task.get() logging.root.setLevel(self.conn.call_sync('management.get_logging_level')) setproctitle.setproctitle('task executor (tid {0})'.format(task['id'])) if task['debugger']: sys.path.append('/usr/local/lib/dispatcher/pydev') import pydevd host, port = task['debugger'] pydevd.settrace(host, port=port, stdoutToServer=True, stderrToServer=True) name, _ = os.path.splitext(os.path.basename(task['filename'])) module = load_module_from_file(name, task['filename']) setproctitle.setproctitle('task executor (tid {0})'.format(task['id'])) fds = list(self.collect_fds(task['args'])) try: self.instance = getattr(module, task['class'])(DispatcherWrapper(self.conn), self.datastore) self.instance.configstore = self.configstore self.instance.user = task['user'] self.instance.environment = task['environment'] self.running.set() result = self.instance.run(*task['args']) except BaseException as err: print("Task exception: {0}".format(str(err)), file=sys.stderr) traceback.print_exc(file=sys.stderr) if hasattr(self.instance, 'rollback'): self.put_status('ROLLBACK') try: self.instance.rollback(*task['args']) except BaseException as rerr: print("Task exception during rollback: {0}".format(str(rerr)), file=sys.stderr) traceback.print_exc(file=sys.stderr) self.put_status('FAILED', exception=err) else: self.put_status('FINISHED', result=result) finally: self.close_fds(fds) self.running.clear() except RpcException as err: print("RPC failed: {0}".format(str(err)), file=sys.stderr) print(traceback.format_exc(), flush=True) sys.exit(errno.EBADMSG) except socket.error as err: print("Cannot connect to dispatcher: {0}".format(str(err)), file=sys.stderr) sys.exit(errno.ETIMEDOUT) if task['debugger']: import pydevd pydevd.stoptrace() setproctitle.setproctitle('task executor (idle)')
def detach(self): import pydevd pydevd.stoptrace()