简体   繁体   中英

How can I "import apt" from within a virtualenv?

I have written a Python utility script that relies on the Debian package python3-apt :

import apt

...

def get_packages():
    cache = apt.Cache()
    for pkg in cache:
        if pkg.installed and pkg.name in PACKAGE_LIST:
            yield pkg.name

I am now expanding the script into a project, with the eventual intent of making it available on PyPI and/or as a Debian package itself.

I use virtualenvs to isolate my Python development environments. What package name (or path) do I need to add to my virtualenv so that I can call import apt from within that environment?

So far I have tried:

You can achieve this with pipenv as follows (similar instructions should work for other venv managers):

pipenv --site-packages  # see note 1
PIP_IGNORE_INSTALLED=1 pipenv install  # see note 2

You are more likely to run this as:

pipenv --site-packages
PIP_IGNORE_INSTALLED=1 pipenv install -e . --dev
# treats codebase as a package, also installs dev dependencies

Note 1: We must access system packages (aka site packages) so that we can import apt .

Note 2: ...but we prefer virtualenv packages to system packages. See https://pipenv.pypa.io/en/latest/advanced/#working-with-platform-provided-python-components for details.

Comments:

  • This means that all other system packages not defined in your Pipfile are also available in your venv. You must remember that they aren't necessarily available to other developers using the same codebase. If you have a basic CI environment, it should catch this.

  • This approach will work for other packages not supported by vext.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM