def wait_for_attach(): PORT = 3001 Debug('Waiting for debugger to attach to port %i...' % PORT) # import ptvsd # ptvsd.enable_attach(address=('127.0.0.1', PORT)) #, redirect_output=True) # ptvsd.wait_for_attach() import debugpy debugpy.listen(PORT) debugpy.wait_for_client()
def debug(): # pragma: no cover """Start debugpy debugger.""" debugpy.listen(("0.0.0.0", 10001)) print( "โณ VS Code debugger can now be attached, press F5 in VS Code โณ", flush=True, ) debugpy.wait_for_client() print("๐ VS Code debugger attached, enjoy debugging ๐", flush=True)
def debugpy_init(port=5678): if get_environment() == "development": import debugpy print("running in debug mode") try: debugpy.listen(("0.0.0.0", port)) debugpy.wait_for_client() except Exception: print(f"debugpy attach on port {port} aborted")
def initialize_flask_server_debugger_if_needed(): print('*** ***') if getenv("FLASK_DEBUG") == "True": import debugpy debugpy.listen(("0.0.0.0", 5713)) print("โณ VS Code debugger can now be attached, press F5 in VS Code โณ", flush=True) debugpy.wait_for_client() print("๐ VS Code debugger attached, enjoy debugging ๐", flush=True)
def initialize_debugger(): import multiprocessing if multiprocessing.current_process().pid > 1: import debugpy debugpy.listen(("0.0.0.0", DEBUGPORT)) print("Debugger is ready to be attached, press F5", flush=True) debugpy.wait_for_client() print("Visual Studio Code debugger is now attached", flush=True)
def __init__(self): self.config = Config().config self.gcloud = False self.debug = False if 'REMOTE_DEBUG' in os.environ: import debugpy self.debug = True debugpy.listen(("0.0.0.0", 5678)) debugpy.wait_for_client()
def start_debug_for_vscode() -> None: """VSCodeใฎใใใใฌใผใใขใฟใใๅฏ่ฝใชใขใใชใฑใผใทใงใณใตใผใใ่ตทๅใใพใ""" import debugpy import uvicorn # ใใใใฌใผใใขใฟใใใใใใพใงๅพ ๆฉใใฆใใใขใใชใฑใผใทใงใณใ่ตทๅใใ debugpy.listen(("0.0.0.0", 5678)) debugpy.wait_for_client() uvicorn.run("src.api:app", host="0.0.0.0", port=8080, reload=True)
def init_debugger(): import multiprocessing if multiprocessing.current_process().pid > 1: import debugpy debugpy.listen(("0.0.0.0", 10000)) print("โณ VS Code debugger can now be attached, press F5 in VS Code โณ", flush=True) debugpy.wait_for_client() print("๐ VS Code debugger attached ๐")
def main(): if 'REMOTE_DEBUG' in os.environ: print("Starting remote debugger on port 5678") import debugpy debugpy.listen(("0.0.0.0", 5678)) print("Waiting for connection...") debugpy.wait_for_client() args = docopt(__doc__, version='fcreplay 0.9.1') # Setup logging if not checking or generating config if not args['config']: fclogging.setup_logger() if args['tasker']: if args['start']: if args['recorder']: if '--max_instances' in args: Tasker().recorder(max_instances=args['--max_instances']) else: Tasker().recorder() if args['check_top_weekly']: Tasker().check_top_weekly() if args['check_video_status']: Tasker().check_video_status() elif args['cli']: c = Cli() sys.exit(c.cmdloop()) elif args['config']: if args['validate']: Config().validate_config_file(args['<config.json>']) if args['generate']: Config().generate_config() elif args['get']: if args['game']: Getreplay().get_game_replays(game=args['<gameid>']) if args['ranked']: Getreplay().get_ranked_replays(game=args['<gameid>'], username=args['--playerid'], pages=args['--pages']) if args['replay']: Getreplay().get_replay(url=args['<url>'], player_requested=args['--playerrequested']) if args['weekly']: Getreplay().get_top_weekly() elif args['instance']: i = Instance() i.debug = args['--debug'] i.main()
def initialize_flask_server_debugger_if_needed(): if getenv("DEBUGGER") == "True": import multiprocessing if multiprocessing.current_process().pid > 1: import debugpy debugpy.listen(("0.0.0.0", 4001)) print("โณ VS Code debugger can now be attached, press F5 in VS Code โณ", flush=True) debugpy.wait_for_client() print("๐ VS Code debugger attached, enjoy debugging ๐", flush=True)
def start_remote_debug(): """ Start remote debugging from level 2 and wait on it from level 3""" runtime_system = RuntimeSystem() if config.DEBUG_LEVEL > 1 and runtime_system.is_target_system: import debugpy # pylint: disable=import-outside-toplevel port = 3003 debugpy.listen(("0.0.0.0", port)) if config.DEBUG_LEVEL > 2: print("Waiting to attach on port %s", port) debugpy.wait_for_client( ) # blocks execution until client is attached
def debugpy_start(): #if getenv("DEBUGGER") == "True": if 1==1: import multiprocessing if multiprocessing.current_process().pid > 1: import debugpy debugpy.listen(("0.0.0.0", 5678)) print("โณ VS Code debugger can now be attached, press F5 in VS Code โณ", flush=True) debugpy.wait_for_client() print("๐ VS Code debugger attached, enjoy debugging ๐", flush=True)
def main(debug: bool = False, eager: bool = False): if debug: import debugpy print("Waiting for debugger...") debugpy.listen(5678) debugpy.wait_for_client() X_train, _1, X_test, _2 = dataget.image.mnist(global_cache=True).get() # Now binarize data X_train = (X_train > 0).astype(jnp.float32) X_test = (X_test > 0).astype(jnp.float32) print("X_train:", X_train.shape, X_train.dtype) print("X_test:", X_test.shape, X_test.dtype) model = elegy.Model( module=VariationalAutoEncoder.defer(), loss=[KLDivergence(), BinaryCrossEntropy(on="logits")], optimizer=optix.adam(1e-3), run_eagerly=eager, ) epochs = 10 # Fit with datasets in memory history = model.fit( x=X_train, epochs=epochs, batch_size=64, steps_per_epoch=100, validation_data=(X_test, ), shuffle=True, ) plot_history(history) # get random samples idxs = np.random.randint(0, len(X_test), size=(5, )) x_sample = X_test[idxs] # get predictions y_pred = model.predict(x=x_sample) # plot results plt.figure(figsize=(12, 12)) for i in range(5): plt.subplot(2, 5, i + 1) plt.imshow(x_sample[i], cmap="gray") plt.subplot(2, 5, 5 + i + 1) plt.imshow(y_pred["image"][i], cmap="gray") plt.show()
def setup(address, path_mappings): global EDITOR_ADDRESS, OWN_SERVER_PORT, DEBUGPY_PORT EDITOR_ADDRESS = address OWN_SERVER_PORT = start_own_server() DEBUGPY_PORT = start_debug_server() send_connection_information(path_mappings) print("Waiting for debug client.") debugpy.wait_for_client() print("Debug client attached.")
def debug(self): if Config.configured: log.debug('udebug can be configured only once') return Config.configured = True debugpy.log_to(Config.logto) # in vs code debuger select attach, port = 5678 # commands in shell: # py:debug-start debugpy.listen((Config.host, Config.port)) debugpy.wait_for_client()
def __init__(self): parser = argparse.ArgumentParser( formatter_class=CustomFormatter, description='Tool to manage ZFS clones with history metadata') parser.add_argument('-V', '--version', help='Print version information and quit', action='version', version='%(prog)s version ' + __version__) parser.add_argument( '-l', '--log-level', help= 'Set the logging level ("debug"|"info"|"warn"|"error"|"fatal")', choices=['debug', 'info', 'warn', 'error', 'critical', 'none'], metavar='LOG_LEVEL', default='none') parser.add_argument('-D', '--debug', help='Enable debug mode', action='store_true') parser.add_argument('-q', '--quiet', help='Enable quiet mode', action='store_true') subparsers = parser.add_subparsers(dest='command', metavar='COMMAND', required=True) for command in CLI.commands: command.init_parser(subparsers) options = parser.parse_args() set_log_level(options.log_level) if options.debug: import debugpy debugpy.listen(('0.0.0.0', 5678)) log.info("Waiting for IDE to attach...") debugpy.wait_for_client() try: for command in self.commands: if options.command == command.name or options.command in command.aliases: command(options) break except ZCMException as e: log.error(e.message) print(e.message) exit(-1)
def worker(): print("====================== worker") import debugpy # debugpy.listen(("0.0.0.0", 5678)) debugpy.listen(5678) debugpy.wait_for_client() # debugpy.breakpoint() i = 0 while i < 10: print(i) i = i + 1
def initialize_flask_server_debugger_if_needed(): if app.config.get('DEBUG'): import multiprocessing if multiprocessing.current_process().pid > 1: import debugpy debugpy.listen(('0.0.0.0', 10001)) print( 'โณ VS Code debugger can now be attached, press F5 in VS Code โณ', flush=True) debugpy.wait_for_client() print('๐ VS Code debugger attached, enjoy debugging ๐', flush=True)
def supervisor_debugger(coresys: CoreSys) -> None: """Start debugger if needed.""" if not coresys.config.debug: return # pylint: disable=import-outside-toplevel import debugpy _LOGGER.info("Initializing Supervisor debugger") debugpy.listen(("0.0.0.0", 33333)) if coresys.config.debug_block: _LOGGER.info("Wait until debugger is attached") debugpy.wait_for_client()
def initialize_debugger(): import debugpy # optionally check to see what env you're running in, you probably only want this for # local development, for example: if os.getenv("MY_ENV") == "dev": # RUN_MAIN envvar is set by the reloader to indicate that this is the # actual thread running Django. This code is in the parent process and # initializes the debugger if not os.getenv("RUN_MAIN"): debugpy.listen(("0.0.0.0", 5678)) sys.stdout.write("Start the VS Code debugger now, waiting...\n") debugpy.wait_for_client() sys.stdout.write("Debugger attached, starting server...\n")
def POST(self): import debugpy i = web.input() # Allow other computers to attach to ptvsd at this IP address and port. logger.info("Enabling debugger attachment") debugpy.listen(address=('0.0.0.0', 3000)) logger.info("Waiting for debugger to attach...") debugpy.wait_for_client() logger.info("Debugger attached to port 3000") add_flash_message("info", "Debugger attached!") return self.GET()
def load_debugger(secret, port, mixed_mode): try: if secret and port: # Start tests with legacy debugger import ptvsd from ptvsd.debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code from ptvsd import enable_attach, wait_for_attach DONT_DEBUG.append(os.path.normcase(__file__)) DEBUG_ENTRYPOINTS.add(get_code(main)) enable_attach(secret, ('127.0.0.1', port), redirect_output=True) wait_for_attach() elif port: # Start tests with new debugger import debugpy debugpy.listen(('localhost', port)) debugpy.wait_for_client() elif mixed_mode: # For mixed-mode attach, there's no ptvsd and hence no wait_for_attach(), # so we have to use Win32 API in a loop to do the same thing. from time import sleep from ctypes import windll, c_char while True: if windll.kernel32.IsDebuggerPresent() != 0: break sleep(0.1) try: debugger_helper = windll[ 'Microsoft.PythonTools.Debugger.Helper.x86.dll'] except WindowsError: debugger_helper = windll[ 'Microsoft.PythonTools.Debugger.Helper.x64.dll'] isTracing = c_char.in_dll(debugger_helper, "isTracing") while True: if isTracing.value != 0: break sleep(0.1) except: traceback.print_exc() print(''' Internal error detected. Please copy the above traceback and report at https://github.com/Microsoft/vscode-python/issues/new Press Enter to close. . .''') try: raw_input() except NameError: input() sys.exit(1)
def start_debug( id="python", host="127.0.0.1", port=8989, timeout=10, debugpy_host="127.0.0.1", debugpy_port=4567, debugpy_port_autoincrement=True, ): global _this_process_attached if _this_process_attached: return 0 try: sock = socket.create_connection((host, port)) except Exception: print(f"Cannot connect to {host}:{port}", file=sys.stderr) return -1 try: while True: try: if 0 > debugpy_port or debugpy_port > 0xFFFF: print("debugpy port number is out of range") return -2 debugpy.listen(debugpy_port) print(f"debugpy is listening port {debugpy_port}", file=sys.stderr) break except RuntimeError: if debugpy_port_autoincrement: debugpy_port += 1 else: print(f"Cannot listen to port {debugpy_port}") return -2 sock.settimeout(timeout) sock.send( bytes(f"{id}\r\n{debugpy_host}\r\n{debugpy_port}\r\n", "utf8")) ret_code = sock.recv(1)[0] except Exception as e: print(f"Communication error {e}", file=sys.stderr) return -2 finally: sock.close() if ret_code == 0: _this_process_attached = True debugpy.wait_for_client() return ret_code
def main( debug: bool = False, eager: bool = False, logdir: str = "runs", steps_per_epoch: int = 200, epochs: int = 100, batch_size: int = 64, ): if debug: import debugpy print("Waiting for debugger...") debugpy.listen(5678) debugpy.wait_for_client() current_time = datetime.now().strftime("%b%d_%H-%M-%S") logdir = os.path.join(logdir, current_time) dataset = load_dataset("mnist") dataset.set_format("np") X_train = np.stack(dataset["train"]["image"]) y_train = dataset["train"]["label"] X_test = np.stack(dataset["test"]["image"]) y_test = dataset["test"]["label"] print("X_train:", X_train.shape, X_train.dtype) print("y_train:", y_train.shape, y_train.dtype) print("X_test:", X_test.shape, X_test.dtype) print("y_test:", y_test.shape, y_test.dtype) model = Model( features_out=10, optimizer=optax.adam(1e-3), eager=eager, ) history = model.fit( inputs=X_train, labels=y_train, epochs=epochs, steps_per_epoch=steps_per_epoch, batch_size=batch_size, validation_data=(X_test, y_test), shuffle=True, callbacks=[eg.callbacks.TensorBoard(logdir=logdir)], ) eg.utils.plot_history(history)
def _entry_debug_server(self): import debugpy debugpy.listen(self._endpoint) while self._running: debugpy.wait_for_client() debugpy.breakpoint() # While we are connected to the debugger, have the debug assistant # thread loop while debugpy.is_client_connected(): time.sleep(2) return
def check_and_enable_debugpy(): # These could either come from settings or environment debugpy_enable = forcebool(os.getenv('DEBUGPY_ENABLE', getattr(settings, 'DEBUGPY_ENABLE', False))) debugpy_wait_for_attach = forcebool(os.getenv('DEBUGPY_WAIT_FOR_ATTACH', getattr(settings, 'DEBUGPY_WAIT_FOR_ATTACH', False))) debugpy_address = os.getenv('DEBUGPY_REMOTE_ADDRESS', getattr(settings, 'DEBUGPY_REMOTE_ADDRESS', '0.0.0.0')) debugpy_port = os.getenv('DEBUGPY_REMOTE_PORT', getattr(settings, 'DEBUGPY_REMOTE_PORT', '5678')) if debugpy_enable: import debugpy debugpy.listen((debugpy_address, int(debugpy_port))) logger.info('DEBUGPY: Enabled Listen ({0}:{1})'.format(debugpy_address, debugpy_port)) if debugpy_wait_for_attach: logger.info('DEBUGPY: Waiting for attach...') debugpy.wait_for_client()
def construct_debug(self, node): print("Construct_debug") if os.environ.get('DEBUG'): import debugpy print("Starting debugging.") debugpy_port = os.environ.get("DEBUG_PORT", 5678) print(debugpy_port) try: debugpy.listen(("0.0.0.0", 6051)) debugpy.wait_for_client() print("Started debugpy at port %s." % debugpy_port) except OSError: print("debugpy port %s already in use." % debugpy_port) breakpoint() return "2"
def debug(self): if Config.configured: log.debug('udebug can be configured only once') return if not Config.configured: Config.configured = True debugpy.log_to(Config.logto) # in vs code debuger select attach, port = 5678 # commands in shell: # py:debug # elsewhere in python code: # import debugpy # debugpy.breakpoint() debugpy.listen((Config.host, Config.port)) debugpy.wait_for_client()
def initialize_vscode_debug(self): # sys.modules['ctypes'] = '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/' # sys.modules['ctypes'] = '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/' # sys.modules['subprocess'] = '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/' try: # sys.path.append('/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python') sys.path.insert( 0, '/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python' ) except: debug('couldnt append path') self._log_version_data() import debugpy debugpy.listen(5678) debugpy.wait_for_client()
def setup_debugpy_server(debug_enabled, wait_for_client=False): """ If debugging is enabled, then configures the debugpy server and waits for a client connect. NOTE: The wait for the client is blocking. """ if debug_enabled: log.info( f"Debugging enabled, debugpy server listening on {settings.DEBUGPY_ADDRESS}:{settings.DEBUGPY_PORT}." ) import debugpy debugpy.listen((settings.DEBUGPY_ADDRESS, settings.DEBUGPY_PORT)) if wait_for_client: log.warn("Blocking to wait for a debugpy client connection...") debugpy.wait_for_client() log.info("debugpy client attached.")