py_write_requirements()writes the requirements currently tracked bypy_require(). Iffreeze = TRUEor if thepythonenvironment is not ephemeral, it writes a fully resolved manifest viapip freeze.py_read_requirements()readsrequirements.txtand.python-version, and applies them withpy_require(). By default, entries are added (action = "add").
These are primarily an alternative interface to py_require(), but can
also work with non-ephemeral virtual environments.
Arguments
- packages
 Path to the package requirements file. Defaults to
"requirements.txt". UseNULLto skip.- python_version
 Path to the Python version file. Defaults to
".python-version". UseNULLto skip.- ...
 Unused; must be empty.
- freeze
 Logical. If
TRUE, writes a fully resolved list of installed packages usingpip freeze. IfFALSE, writes only the requirements tracked bypy_require().- python
 Path to the Python executable to use.
- quiet
 Logical; if
TRUE, suppresses the informational messages that printwrote '<path>'for each file written.- action
 How to apply requirements read by
py_read_requirements():"add"(default) adds to existing requirements,"set"replaces them,"remove"removes matching entries, or"none"skips applying them and returns the read values.
Value
Invisibly, a list with two named elements:
packagesCharacter vector of package requirements.
python_versionString specifying the Python version.
To get just the return value without writing any files, you can pass
NULL for file paths, like this:
py_write_requirements(NULL, NULL)
py_write_requirements(NULL, NULL, freeze = TRUE)Note
To continue using py_require() locally while keeping a
requirements.txt up-to-date for deployments, you can register
an exit handler in .Rprofile like this:
reg.finalizer(
  asNamespace("reticulate"),
  function(ns) {
    if (
      reticulate::py_available() &&
        isTRUE(reticulate::py_config()$ephemeral)
    ) {
      reticulate::py_write_requirements(quiet = TRUE)
    }
  },
  onexit = TRUE
)This approach is only recommended if you are using git.
Alternatively, you can transition away from using ephemeral python
environemnts via py_require() to using a persistent local virtual
environment you manage. You can create a local virtual environment from
requirements.txt and .python-version using virtualenv_create():
# Note: '.venv' in the current directory is auto-discovered by reticulate.
# https://rstudio.github.io/reticulate/articles/versions.html#order-of-discovery
virtualenv_create(
  "./.venv",
  version = readLines(".python-version"),
  requirements = "requirements.txt"
)If you run into issues, be aware that requirements.txt and
.python-version may not contain all the information necessary to
reproduce the Python environment if the R code sets environment variables
like UV_INDEX or UV_CONSTRAINT.