Using Locust as a library

It’s possible to use Locust as a library instead of running Locust by invoking the locust command.

Here’s an example:

import gevent
from locust import HttpLocust, TaskSet, task, between
from locust.runners import LocalLocustRunner
from locust.env import Environment
from locust.stats import stats_printer
from locust.log import setup_logging
from locust.web import WebUI

setup_logging("INFO", None)

class User(HttpLocust):
    wait_time = between(1, 3)
    host = ""

    class task_set(TaskSet):
        def my_task(self):

        def task_404(self):

# setup Environment and Runner
env = Environment()
runner = LocalLocustRunner(environment=env, locust_classes=[User])
# start a WebUI instance
web_ui = WebUI(environment=env)
gevent.spawn(lambda: web_ui.start("", 8089))

# start a greenlet that periodically outputs the current stats

# start the test
runner.start(1, hatch_rate=10)
# wait for the greenlets (indefinitely)