Esempio n. 1
0
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()
Esempio n. 2
0
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)
Esempio n. 3
0
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")
Esempio n. 4
0
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)
Esempio n. 5
0
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)
Esempio n. 6
0
    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()
Esempio n. 7
0
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)
Esempio n. 8
0
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 🎉")
Esempio n. 9
0
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()
Esempio n. 10
0
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)
Esempio n. 11
0
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
Esempio n. 12
0
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)
Esempio n. 13
0
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()
Esempio n. 14
0
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.")
Esempio n. 15
0
File: udebug.py Progetto: m32/far2l
    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()
Esempio n. 16
0
    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)
Esempio n. 17
0
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
Esempio n. 18
0
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)
Esempio n. 19
0
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()
Esempio n. 20
0
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")
Esempio n. 21
0
    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()
Esempio n. 22
0
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)
Esempio n. 23
0
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
Esempio n. 24
0
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)
Esempio n. 25
0
    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
Esempio n. 26
0
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()
Esempio n. 27
0
 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"
Esempio n. 28
0
    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()
Esempio n. 29
0
File: debug.py Progetto: aumhaa/m4m8
 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()
Esempio n. 30
0
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.")