Search code examples
locust

locust unrecognized arguments when running as lib


The following codes are from Locust examples - use_as_lib.

import gevent
from locust import HttpUser, task
from locust.env import Environment
from locust.stats import stats_printer, stats_history
from locust.log import setup_logging

setup_logging("INFO", None)


class MyUser(HttpUser):
    host = "https://docs.locust.io"

    @task
    def t(self):
        self.client.get("/")


env = Environment(user_classes=[MyUser])
runner = env.create_local_runner()

web_ui = env.create_web_ui("127.0.0.1", 8089)

env.events.init.fire(environment=env, runner=runner, web_ui=web_ui)

gevent.spawn(stats_printer(env.stats))

gevent.spawn(stats_history, env.runner)

runner.start(1, spawn_rate=10)

gevent.spawn_later(60, lambda: runner.quit())

runner.greenlet.join()

web_ui.stop()

If I run it with python use_as_lib.py, everything works fine. But if I run it with python use_as_lib.py -c argument01 -b argument02, it will fail with:

use_as_lib.py: error: unrecognized arguments: -c -b argument02

In my case, the snippet above is part of a big program, which has its own command line arguments.

I checked a bit, seems argument_parser.ui_extra_args_dict() here invoked by env.create_web_ui("127.0.0.1", 8089) will parse all the arguments, which cause this issue.

Any ideas on how to fix it ? Thanks!


Solution

  • You can pass a parsed set of parameters when you create the environment, slightly less hack-y than your suggestion. Something like this:

    parser = locust.argument_parser.get_parser() 
    parsed_options = parser.parse_args("-f yourlocustfile.py --headless <other params>")
    env = Environment(user_classes=[MyUser], parsed_options=parsed_options=parsed_options)
    

    Would that work?