Best Python code snippet using locust
main.py
Source:main.py  
...289        # spawn stats printing greenlet290        stats_printer_greenlet = gevent.spawn(stats_printer(runner.stats))291        stats_printer_greenlet.link_exception(greenlet_exception_handler)292    gevent.spawn(stats_history, runner)293    def start_automatic_run():294        if options.master:295            # wait for worker nodes to connect296            start_time = time.monotonic()297            while len(runner.clients.ready) < options.expect_workers:298                if options.expect_workers_max_wait and options.expect_workers_max_wait < time.monotonic() - start_time:299                    logger.error("Gave up waiting for workers to connect.")300                    runner.quit()301                    sys.exit(1)302                logging.info(303                    "Waiting for workers to be ready, %s of %s connected",304                    len(runner.clients.ready),305                    options.expect_workers,306                )307                # TODO: Handle KeyboardInterrupt and send quit signal to workers that are started.308                #       Right now, if the user sends a ctrl+c, the master will not gracefully309                #       shutdown resulting in all the already started workers to stay active.310                time.sleep(1)311        if not options.worker:312            # apply headless mode defaults313            if options.num_users is None:314                options.num_users = 1315            if options.spawn_rate is None:316                options.spawn_rate = 1317            # start the test318            if environment.shape_class:319                if options.run_time:320                    sys.stderr.write("It makes no sense to combine --run-time and LoadShapes. Bailing out.\n")321                    sys.exit(1)322                environment.runner.start_shape()323                environment.runner.shape_greenlet.join()324                stop_and_optionally_quit()325            else:326                headless_master_greenlet = gevent.spawn(runner.start, options.num_users, options.spawn_rate)327                headless_master_greenlet.link_exception(greenlet_exception_handler)328        if options.run_time:329            logger.info(f"Run time limit set to {options.run_time} seconds")330            spawn_run_time_quit_greenlet()331        elif not options.worker and not environment.shape_class:332            logger.info("No run time limit set, use CTRL+C to interrupt")333    if options.csv_prefix:334        gevent.spawn(stats_csv_writer.stats_writer).link_exception(greenlet_exception_handler)335    if options.headless:336        start_automatic_run()337    input_listener_greenlet = None338    if not options.worker:339        # spawn input listener greenlet340        input_listener_greenlet = gevent.spawn(341            input_listener(342                {343                    "w": lambda: runner.start(runner.user_count + 1, 100)344                    if runner.state != "spawning"345                    else logging.warning("Already spawning users, can't spawn more right now"),346                    "W": lambda: runner.start(runner.user_count + 10, 100)347                    if runner.state != "spawning"348                    else logging.warning("Already spawning users, can't spawn more right now"),349                    "s": lambda: runner.start(max(0, runner.user_count - 1), 100)350                    if runner.state != "spawning"351                    else logging.warning("Spawning users, can't stop right now"),352                    "S": lambda: runner.start(max(0, runner.user_count - 10), 100)353                    if runner.state != "spawning"354                    else logging.warning("Spawning users, can't stop right now"),355                },356            )357        )358        input_listener_greenlet.link_exception(greenlet_exception_handler)359        # ensure terminal is reset, even if there is an unhandled exception in locust or someone360        # does something wild, like calling sys.exit() in the locustfile361        atexit.register(input_listener_greenlet.kill, block=True)362    def shutdown():363        """364        Shut down locust by firing quitting event, printing/writing stats and exiting365        """366        logger.debug("Running teardowns...")367        if input_listener_greenlet is not None:368            input_listener_greenlet.kill(block=False)369        environment.events.quitting.fire(environment=environment, reverse=True)370        # determine the process exit code371        if environment.process_exit_code is not None:372            code = environment.process_exit_code373        elif len(runner.errors) or len(runner.exceptions):374            code = options.exit_code_on_error375        elif log.unhandled_greenlet_exception:376            code = 2377        else:378            code = 0379        logger.info(f"Shutting down (exit code {code})")380        if stats_printer_greenlet is not None:381            stats_printer_greenlet.kill(block=False)382        if headless_master_greenlet is not None:383            headless_master_greenlet.kill(block=False)384        logger.debug("Cleaning up runner...")385        if runner is not None:386            runner.quit()387        if not isinstance(runner, locust.runners.WorkerRunner):388            print_stats(runner.stats, current=False)389            print_percentile_stats(runner.stats)390            print_error_report(runner.stats)391        environment.events.quit.fire(exit_code=code)392        sys.exit(code)393    # install SIGTERM handler394    def sig_term_handler():395        logger.info("Got SIGTERM signal")396        shutdown()397    def save_html_report():398        html_report = get_html_report(environment, show_download_link=False)399        logger.info("writing html report to file: %s", options.html_file)400        with open(options.html_file, "w", encoding="utf-8") as file:401            file.write(html_report)402    gevent.signal_handler(signal.SIGTERM, sig_term_handler)403    try:404        logger.info(f"Starting Locust {version}")405        if options.autostart:406            start_automatic_run()407        main_greenlet.join()408        if options.html_file:409            save_html_report()410    except KeyboardInterrupt:411        if options.html_file:412            save_html_report()413    except Exception:414        raise...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
