Runner Script
The behave CLI is a thin wrapper around a callable runner, which means you can launch the same engine from a Python script. A runner script is useful for CI entry points, for wrapping the run with your own setup, and for capturing the exit code in another language's tooling.
Calling behave.main
#!/usr/bin/env python3
"""run_tests.py - launch the behave suite from Python."""
from behave import main
if __name__ == "__main__":
exit(main(["features/", "-t", "not @wip"]))
main accepts an optional argument list with exactly the same options as the CLI. Without arguments it behaves like a bare behave invocation. The process exit code is the behave exit code: 0 when everything passed, non-zero otherwise.
Wrapping the Run
Because the call is just a function, you can do work before and after it: create a test database, time the run, and always tear down, even on failure:
import time
from behave import main
from testdb import create_test_db, drop_test_db
db = create_test_db()
start = time.time()
try:
exit_code = main(["features/", "-f", "junit", "-o", "reports"])
finally:
drop_test_db()
print(f"behave exited with {exit_code} in {time.time() - start:.1f}s")
raise SystemExit(exit_code)
Parsing the Result in Python
If you need more than the exit code, let behave write its JSON report and parse it instead of scraping the console:
import json
from behave import main
main(["features/", "-f", "json", "-o", "reports/report.json"])
with open("reports/report.json") as fh:
run = json.load(fh)
failed_scenarios = [
s["id"] for f in run for s in f["scenarios"]
if s["status"] == "failed"
]
print("failed:", failed_scenarios or "none")
Using It in CI
Reference the script from your CI configuration so the environment (virtualenv, environment variables, service startup) is set up in one place:
python3 run_tests.py
echo "exit: $?"
Summary
Call behave.main(args) from a Python script to control the run programmatically. Wrap it with your own setup and teardown, and read the JSON report (not the console) for structured results.