pythonpipsubprocessrequirements.txttox

How do I freeze the requirements of a tox test environment?


I usually install my requirements from an abstract file like so:

# requirements.in
pytest

I define test environments in a tox.ini like so:

[testenv]
deps = -rrequirements.in
commands = pytest

How do I freeze the installed versions of the dependencies to a requirements.txt file?

I tried using this bash one-liner:

commands_post = python -m pip freeze --all > requirements.d/pytest.txt

However, this prints the requirements to the standard output instead of redirecting them to the file:

pytest-py312: commands_post[0]> python -m pip freeze --all '>' requirements.d/pytest.txt

Note that the > is getting escaped instead of being interpreted.


Solution

  • One solution to this is to allow using bash and run the pip freeze command inside bash:

    [testenv]
    allowlist_externals = bash,/bin/bash,/usr/bin/bash
    commands = pytest
    commands_post = bash -c "python -m pip freeze --all > requirements.d/pytest.txt"
    deps = -rrequirements.in
    

    Note: This solution is not portable to systems without bash.