Sean Mackesey
Sean Mackesey

Reputation: 10939

Python: Set PYTHONPATH according to requirements.txt at runtime

I have a Python application that comes with a command line script. I expose the script via setuptools "entry point" feature. Whenever a user runs the script, I would like the environment to be consistent with the package's requirements.txt. This means that the environment must contain versions of each dependency package that match the version specifiers in requirements.txt.

I know that this can be achieved with venv/virtualenv by making my users create a virtual environment, install requirements.txt in it, and activate that virtual environment whenever they run the script. I do not want to impose this burden of manually invoking virtualenv on users. Ruby's bundler solves this problem by providing bundler/setup-- when loaded, it modifies Ruby's $LOAD_PATH to reflect the contents of the Gemfile (analogue of requirements.txt). Thus it can be placed at the top of a script to transparently control the runtime environment. Does Python have an equivalent? That is, a way to set the environment at runtime according to requirements.txt without imposing additional complexity on the user?

Upvotes: 2

Views: 1390

Answers (2)

Piotr Dobrogost
Piotr Dobrogost

Reputation: 42425

Does Python have an equivalent? That is, a way to set the environment at runtime according to requirements.txt without imposing additional complexity on the user?

Yes, more than one.

One is pex

pex is a library for generating .pex (Python EXecutable) files which are executable Python environments in the spirit of virtualenvs.

and the other is Platter:

Platter is a tool for Python that simplifies deployments on Unix servers. It’s a thin wrapper around pip, virtualenv and wheel and aids in creating packages that can install without compiling or downloading on servers.

Upvotes: 1

Markus Unterwaditzer
Markus Unterwaditzer

Reputation: 8244

I don't see why it wouldn't be possible for a Python program to install its own dependencies before importing them, but it is unheard of in the Python community.

I'd rather look at options to make your application a standalone executable, as explained here, for instance.

Upvotes: 1

Related Questions