Configuration & API

Noxfile

Nox looks for configuration in a file named noxfile.py by default. You can specify a different file using the --noxfile argument when running nox.

Defining sessions

session(func: F | None = None, python: str | Sequence[str] | bool | None = None, py: str | Sequence[str] | bool | None = None, reuse_venv: bool | None = None, name: str | None = None, venv_backend: Any | None = None, venv_params: Any | None = None, tags: Sequence[str] | None = None) F | Callable[[F], F]

Designate the decorated function as a session.

Nox sessions are configured via standard Python functions that are decorated with @nox.session. For example:

import nox

@nox.session
def tests(session):
    session.run('pytest')

You can also configure sessions to run against multiple Python versions as described in Configuring a session’s virtualenv and parametrize sessions as described in parametrized sessions.

Session description

You can add a description to your session using a docstring. The first line will be shown when listing the sessions. For example:

import nox

@nox.session
def tests(session):
    """Run the test suite."""
    session.run('pytest')

The nox --list command will show:

$ nox --list
Available sessions:
* tests -> Run the test suite.

Session name

By default Nox uses the decorated function’s name as the session name. This works wonderfully for the vast majority of projects, however, if you need to you can customize the session’s name by using the name argument to @nox.session. For example:

import nox

@nox.session(name="custom-name")
def a_very_long_function_name(session):
    print("Hello!")

The nox --list command will show:

$ nox --list
Available sessions:
* custom-name

And you can tell nox to run the session using the custom name:

$ nox --session "custom-name"
Hello!

Configuring a session’s virtualenv

By default, Nox will create a new virtualenv for each session using the same interpreter that Nox uses. If you installed Nox using Python 3.6, Nox will use Python 3.6 by default for all of your sessions.

You can tell Nox to use a different Python interpreter/version by specifying the python argument (or its alias py) to @nox.session:

@nox.session(python='2.7')
def tests(session):
    pass

Note

The Python binaries on Windows are found via the Python Launcher for Windows (py). For example, Python 3.9 can be found by determining which executable is invoked by py -3.9. If a given test needs to use the 32-bit version of a given Python, then X.Y-32 should be used as the version.

You can also tell Nox to run your session against multiple Python interpreters. Nox will create a separate virtualenv and run the session for each interpreter you specify. For example, this session will run twice - once for Python 2.7 and once for Python 3.6:

@nox.session(python=['2.7', '3.6'])
def tests(session):
    pass

When you provide a version number, Nox automatically prepends python to determine the name of the executable. However, Nox also accepts the full executable name. If you want to test using pypy, for example:

@nox.session(python=['2.7', '3.6', 'pypy-6.0'])
def tests(session):
    pass

When collecting your sessions, Nox will create a separate session for each interpreter. You can see these sessions when running nox --list. For example this Noxfile:

@nox.session(python=['2.7', '3.6', '3.7', '3.8', '3.9'])
def tests(session):
    pass

Will produce these sessions:

* tests-2.7
* tests-3.6
* tests-3.7
* tests-3.8
* tests-3.9

Note that this expansion happens before parameterization occurs, so you can still parametrize sessions with multiple interpreters.

If you want to disable virtualenv creation altogether, you can set python to False, or set venv_backend to "none", both are equivalent. Note that this can be done temporarily through the –no-venv commandline flag, too.

@nox.session(python=False)
def tests(session):
    pass

Use of session.install() is deprecated without a virtualenv since it modifies the global Python environment. If this is what you really want, use session.run() and pip instead.

@nox.session(python=False)
def tests(session):
    session.run("pip", "install", "nox")

You can also specify that the virtualenv should always be reused instead of recreated every time unless --reuse-venv=never:

@nox.session(
    python=['2.7', '3.6'],
    reuse_venv=True)
def tests(session):
    pass

You are not limited to virtualenv, there is a selection of backends you can choose from as venv, conda, mamba, or virtualenv (default):

@nox.session(venv_backend='venv')
def tests(session):
    pass

Finally, custom backend parameters are supported:

@nox.session(venv_params=['--no-download'])
def tests(session):
    pass

Passing arguments into sessions

Often it’s useful to pass arguments into your test session. Here’s a quick example that demonstrates how to use arguments to run tests against a particular file:

@nox.session
def test(session):
    session.install('pytest')

    if session.posargs:
        test_files = session.posargs
    else:
        test_files = ['test_a.py', 'test_b.py']

    session.run('pytest', *test_files)

Now you if you run:

nox

Then nox will run:

pytest test_a.py test_b.py

But if you run:

nox -- test_c.py

Then nox will run:

pytest test_c.py

Parametrizing sessions

Session arguments can be parametrized with the nox.parametrize() decorator. Here’s a typical example of parametrizing the Django version to install:

@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
def tests(session, django):
    session.install(f'django=={django}')
    session.run('pytest')

When you run nox, it will create a two distinct sessions:

$ nox
nox > Running session tests(django='1.9')
nox > python -m pip install django==1.9
...
nox > Running session tests(django='2.0')
nox > python -m pip install django==2.0

nox.parametrize() has an interface and usage intentionally similar to pytest’s parametrize.

parametrize(arg_names: str | Sequence[str], arg_values_list: Iterable[Param | Iterable[Any]] | Param | Iterable[Any], ids: Iterable[str | None] | None = None) Callable[[Any], Any]

Parametrize a session.

Add new invocations to the underlying session function using the list of arg_values_list for the given arg_names. Parametrization is performed during session discovery and each invocation appears as a separate session to Nox.

Parameters:
  • arg_names (Sequence[str]) – A list of argument names.

  • arg_values_list (Sequence[Union[Any, Tuple]]) – The list of argument values determines how often a session is invoked with different argument values. If only one argument name was specified then this is a simple list of values, for example [1, 2, 3]. If N argument names were specified, this must be a list of N-tuples, where each tuple-element specifies a value for its respective argument name, for example [(1, 'a'), (2, 'b')].

  • ids (Sequence[str]) – Optional sequence of test IDs to use for the parametrized arguments.

You can also stack the decorator to produce sessions that are a combination of the arguments, for example:

@nox.session
@nox.parametrize('django', ['1.9', '2.0'])
@nox.parametrize('database', ['postgres', 'mysql'])
def tests(session, django, database):
    ...

If you run nox --list, you’ll see that this generates the following set of sessions:

* tests(database='postgres', django='1.9')
* tests(database='mysql', django='1.9')
* tests(database='postgres', django='2.0')
* tests(database='mysql', django='2.0')

If you only want to run one of the parametrized sessions, see Specifying parametrized sessions.

Giving friendly names to parametrized sessions

The automatically generated names for parametrized sessions, such as tests(django='1.9', database='postgres'), can be long and unwieldy to work with even with using keyword filtering. You can give parametrized sessions custom IDs to help in this scenario. These two examples are equivalent:

@nox.session
@nox.parametrize('django',
    ['1.9', '2.0'],
    ids=['old', 'new'])
def tests(session, django):
    ...
@nox.session
@nox.parametrize('django', [
    nox.param('1.9', id='old'),
    nox.param('2.0', id='new'),
])
def tests(session, django):
    ...

When running nox --list you’ll see their new IDs:

* tests(old)
* tests(new)

And you can run them with nox --sessions "tests(old)" and so on.

This works with stacked parameterizations as well. The IDs are combined during the combination. For example:

@nox.session
@nox.parametrize(
    'django',
    ['1.9', '2.0'],
    ids=["old", "new"])
@nox.parametrize(
    'database',
    ['postgres', 'mysql'],
    ids=["psql", "mysql"])
def tests(session, django, database):
    ...

Produces these sessions when running nox --list:

* tests(psql, old)
* tests(mysql, old)
* tests(psql, new)
* tests(mysql, new)

Parametrizing the session Python

You can use parametrization to select the Python interpreter for a session. These two examples are equivalent:

@nox.session
@nox.parametrize("python", ["3.6", "3.7", "3.8"])
def tests(session):
    ...

@nox.session(python=["3.6", "3.7", "3.8"])
def tests(session):
    ...

The first form can be useful if you need to exclude some combinations of Python versions with other parameters. For example, you may want to test against multiple versions of a dependency, but the latest version doesn’t run on older Pythons:

@nox.session
@nox.parametrize(
    "python,dependency",
    [
        (python, dependency)
        for python in ("3.6", "3.7", "3.8")
        for dependency in ("1.0", "2.0")
        if (python, dependency) != ("3.6", "2.0")
    ],
)
def tests(session, dependency):
    ...

The session object

Nox will call your session functions with an instance of the Session class.

class Session(runner: SessionRunner)

The Session object is passed into each user-defined session function.

This is your primary means for installing package and running commands in your Nox session.

property bin: str

The first bin directory for the virtualenv.

property bin_paths: list[str] | None

The bin directories for the virtualenv.

property cache_dir: Path

Create and return a ‘shared cache’ directory to be used across sessions.

cd(dir: str | PathLike[str]) _WorkingDirContext

An alias for chdir().

chdir(dir: str | PathLike[str]) _WorkingDirContext

Change the current working directory.

Can be used as a context manager to automatically restore the working directory:

with session.chdir("somewhere/deep/in/monorepo"):
    # Runs in "/somewhere/deep/in/monorepo"
    session.run("pytest")

# Runs in original working directory
session.run("flake8")
conda_install(*args: str, auto_offline: bool = True, channel: str | Sequence[str] = '', **kwargs: Any) None

Install invokes conda install to install packages inside of the session’s environment.

To install packages directly:

session.conda_install('pandas')
session.conda_install('numpy', 'scipy')
session.conda_install('dask==2.1.0', channel='conda-forge')

To install packages from a requirements.txt file:

session.conda_install('--file', 'requirements.txt')
session.conda_install('--file', 'requirements-dev.txt')

By default this method will detect when internet connection is not available and will add the –offline flag automatically in that case. To disable this behaviour, set auto_offline=False.

To install the current package without clobbering conda-installed dependencies:

session.install('.', '--no-deps')
# Install in editable mode.
session.install('-e', '.', '--no-deps')

You can specify a conda channel using channel=; a falsey value will not change the current channels. You can specify a list of channels if needed.

Additional keyword args are the same as for run().

create_tmp() str

Create, and return, a temporary directory.

debug(*args: Any, **kwargs: Any) None

Outputs a debug-level message during the session.

property env: dict[str, str]

A dictionary of environment variables to pass into all commands.

error(*args: Any) NoReturn

Immediately aborts the session and optionally logs an error.

install(*args: str, **kwargs: Any) None

Install invokes pip to install packages inside of the session’s virtualenv.

To install packages directly:

session.install('pytest')
session.install('requests', 'mock')
session.install('requests[security]==2.9.1')

To install packages from a requirements.txt file:

session.install('-r', 'requirements.txt')
session.install('-r', 'requirements-dev.txt')

To install the current package:

session.install('.')
# Install in editable mode.
session.install('-e', '.')

Additional keyword args are the same as for run().

Warning

Running session.install without a virtual environment is no longer supported. If you still want to do that, please use session.run("pip", "install", ...) instead.

property interactive: bool

Returns True if Nox is being run in an interactive session or False otherwise.

property invoked_from: str

The directory that Nox was originally invoked from.

Since you can use the --noxfile / -f command-line argument to run a Noxfile in a location different from your shell’s current working directory, Nox automatically changes the working directory to the Noxfile’s directory before running any sessions. This gives you the original working directory that Nox was invoked form.

log(*args: Any, **kwargs: Any) None

Outputs a log during the session.

property name: str

The name of this session.

notify(target: str | SessionRunner, posargs: Iterable[str] | None = None) None

Place the given session at the end of the queue.

This method is idempotent; multiple notifications to the same session have no effect.

A common use case is to notify a code coverage analysis session from a test session:

@nox.session
def test(session):
    session.run("pytest")
    session.notify("coverage")

@nox.session
def coverage(session):
    session.run("coverage")

Now if you run nox -s test, the coverage session will run afterwards.

Parameters:
  • target (Union[str, Callable]) – The session to be notified. This may be specified as the appropriate string (same as used for nox -s) or using the function object.

  • posargs (Optional[Iterable[str]]) – If given, sets the positional arguments only for the queued session. Otherwise, the standard globally available positional arguments will be used instead.

property posargs: list[str]

Any extra arguments from the nox commandline or Session.notify.

property python: str | Sequence[str] | bool | None

The python version passed into @nox.session.

run(*args: str | PathLike[str], env: Mapping[str, str] | None = None, include_outer_env: bool = True, **kwargs: Any) Any | None

Run a command.

Commands must be specified as a list of strings, for example:

session.run('pytest', '-k', 'fast', 'tests/')
session.run('flake8', '--import-order-style=google')

You can not just pass everything as one string. For example, this will not work:

session.run('pytest -k fast tests/')

You can set environment variables for the command using env:

session.run(
    'bash', '-c', 'echo $SOME_ENV',
    env={'SOME_ENV': 'Hello'})

You can extend the shutdown timeout to allow long-running cleanup tasks to complete before being terminated. For example, if you wanted to allow pytest extra time to clean up large projects in the case that Nox receives an interrupt signal from your build system and needs to terminate its child processes:

session.run(
    'pytest', '-k', 'long_cleanup',
    interrupt_timeout=10.0,
    terminate_timeout=2.0)

You can also tell Nox to treat non-zero exit codes as success using success_codes. For example, if you wanted to treat the pytest “tests discovered, but none selected” error as success:

session.run(
    'pytest', '-k', 'not slow',
    success_codes=[0, 5])

On Windows, builtin commands like del cannot be directly invoked, but you can use cmd /c to invoke them:

session.run('cmd', '/c', 'del', 'docs/modules.rst')

If session.run fails, it will stop the session and will not run the next steps. Basically, this will raise a Python exception. Taking this in count, you can use a try...finally block for cleanup runs, that will run even if the other runs fail:

try:
    session.run("coverage", "run", "-m", "pytest")
finally:
    # Display coverage report even when tests fail.
    session.run("coverage", "report")

If you pass silent=True, you can capture the output of a command that would otherwise be shown to the user. For example to get the current Git commit ID:

out = session.run(
    "git", "rev-parse", "--short", "HEAD",
    external=True, silent=True
)

print("Current Git commit is", out.strip())
Parameters:
  • env (dict or None) – A dictionary of environment variables to expose to the command. By default, all environment variables are passed.

  • include_outer_env (bool) – Boolean parameter that determines if the environment variables from the nox invocation environment should be passed to the command. True by default.

  • silent (bool) – Silence command output, unless the command fails. If True, returns the command output (unless the command fails). False by default.

  • success_codes (list, tuple, or None) – A list of return codes that are considered successful. By default, only 0 is considered success.

  • external (bool) – If False (the default) then programs not in the virtualenv path will cause a warning. If True, no warning will be emitted. These warnings can be turned into errors using --error-on-external-run. This has no effect for sessions that do not have a virtualenv.

  • interrupt_timeout (float or None) – The timeout (in seconds) that Nox should wait after it and its children receive an interrupt signal before sending a terminate signal to its children. Set to None to never send a terminate signal. Default: 0.3

  • terminate_timeout (float or None) – The timeout (in seconds) that Nox should wait after it sends a terminate signal to its children before sending a kill signal to them. Set to None to never send a kill signal. Default: 0.2

  • stdout (file or file descriptor) – Redirect standard output of the command into a file. Can’t be combined with silent.

  • stderr (file or file descriptor) – Redirect standard output of the command into a file. Can’t be combined with silent.

run_install(*args: str | PathLike[str], env: Mapping[str, str] | None = None, include_outer_env: bool = True, **kwargs: Any) Any | None

Run a command in the install step.

This is a variant of run() that runs even in the presence of --install-only. This method returns early if --no-install is specified and the virtualenv is being reused. (In nox 2023.04.22 and earlier, this was called run_always, and that continues to be available as an alias.)

Here are some cases where this method is useful:

  • You need to install packages using a command other than pip install or conda install.

  • You need to run a command as a prerequisite of package installation, such as building a package or compiling a binary extension.

Parameters:
  • env (dict or None) – A dictionary of environment variables to expose to the command. By default, all environment variables are passed.

  • include_outer_env (bool) – Boolean parameter that determines if the environment variables from the nox invocation environment should be passed to the command. True by default.

  • silent (bool) – Silence command output, unless the command fails. False by default.

  • success_codes (list, tuple, or None) – A list of return codes that are considered successful. By default, only 0 is considered success.

  • external (bool) – If False (the default) then programs not in the virtualenv path will cause a warning. If True, no warning will be emitted. These warnings can be turned into errors using --error-on-external-run. This has no effect for sessions that do not have a virtualenv.

  • interrupt_timeout (float or None) – The timeout (in seconds) that Nox should wait after it and its children receive an interrupt signal before sending a terminate signal to its children. Set to None to never send a terminate signal. Default: 0.3

  • terminate_timeout (float or None) – The timeout (in seconds) that Nox should wait after it sends a terminate signal to its children before sending a kill signal to them. Set to None to never send a kill signal. Default: 0.2

skip(*args: Any) NoReturn

Immediately skips the session and optionally logs a warning.

property virtualenv: ProcessEnv

The virtualenv that all commands are run in.

warn(*args: Any, **kwargs: Any) None

Outputs a warning during the session.

Modifying Nox’s behavior in the Noxfile

Nox has various command line arguments that can be used to modify its behavior. Some of these can also be specified in the Noxfile using nox.options. For example, if you wanted to store Nox’s virtualenvs in a different directory without needing to pass it into nox every time:

import nox

nox.options.envdir = ".cache"

@nox.session
def tests(session):
    ...

Or, if you wanted to provide a set of sessions that are run by default:

import nox

nox.options.sessions = ["lint", "tests-3.6"]

...

The following options can be specified in the Noxfile:

  • nox.options.envdir is equivalent to specifying –envdir.

  • nox.options.sessions is equivalent to specifying -s or –sessions. If set to an empty list, no sessions will be run if no sessions were given on the command line, and the list of available sessions will be shown instead.

  • nox.options.pythons is equivalent to specifying -p or –pythons.

  • nox.options.keywords is equivalent to specifying -k or –keywords.

  • nox.options.tags is equivalent to specifying -t or –tags.

  • nox.options.default_venv_backend is equivalent to specifying -db or –default-venv-backend.

  • nox.options.force_venv_backend is equivalent to specifying -fb or –force-venv-backend.

  • nox.options.reuse_venv is equivalent to specifying –reuse-venv. Preferred over using nox.options.reuse_existing_virtualenvs.

  • nox.options.reuse_existing_virtualenvs is equivalent to specifying –reuse-existing-virtualenvs. You can force this off by specifying --no-reuse-existing-virtualenvs during invocation. Alias of nox.options.reuse_venv=yes|no.

  • nox.options.stop_on_first_error is equivalent to specifying –stop-on-first-error. You can force this off by specifying --no-stop-on-first-error during invocation.

  • nox.options.error_on_missing_interpreters is equivalent to specifying –error-on-missing-interpreters. You can force this off by specifying --no-error-on-missing-interpreters during invocation.

  • nox.options.error_on_external_run is equivalent to specifying –error-on-external-run. You can force this off by specifying --no-error-on-external-run during invocation.

  • nox.options.report is equivalent to specifying –report.

When invoking nox, any options specified on the command line take precedence over the options specified in the Noxfile. If either --sessions or --keywords is specified on the command line, both options specified in the Noxfile will be ignored.

Nox version requirements

Nox version requirements can be specified in your Noxfile by setting nox.needs_version. If the Nox version does not satisfy the requirements, Nox exits with a friendly error message. For example:

import nox

nox.needs_version = ">=2019.5.30"

@nox.session(name="test")  # name argument was added in 2019.5.30
def pytest(session):
    session.run("pytest")

Any of the version specifiers defined in PEP 440 can be used.

Warning

Version requirements must be specified as a string literal, using a simple assignment to nox.needs_version at the module level. This allows Nox to check the version without importing the Noxfile.