简体   繁体   中英

import local package during poetry run

I just transitioned from pipenv to poetry and I'm having trouble importing a package from a local package I'm developing in a few of my scripts. To make this more concrete, my project looks something like:

pyproject.toml
poetry.lock
bin/
  myscript.py
mypackage/
  __init__.py
  lots_of_stuff.py

Within myscript.py , I import mypackage . But when I poetry run bin/myscript.py I get a ModuleNotFoundError because the PYTHONPATH does not include the root of this project. With pipenv , I could solve that by specifying PYTHONPATH=/path/to/project/root in a .env file, which would be automatically loaded at runtime. What is the right way to import local packages with poetry?

I ran across this piece on using environment variables but export POETRY_PYTHONPATH=/path/to/roject/root doesn't seem to help.

After quite a bit more googling, I stumbled on the packages attribute within the tool.poetry section for pyproject.toml files. To include local packages in distribution, you can specify

# pyproject.toml

[tool.poetry]
# ...
packages = [
    { include = "mypackage" },
]

Now these packages are installed in editable mode:)

Adding a local package (in development) to another project can be done as:

poetry add ./my-package/
poetry add ../my-package/dist/my-package-0.1.0.tar.gz
poetry add ../my-package/dist/my_package-0.1.0.whl

If you want the dependency to be installed in editable mode you can specify it in the pyproject.toml file. It means that changes in the local directory will be reflected directly in environment.

[tool.poetry.dependencies]
my-package = {path = "../my/path", develop = true}

With current preview release (1.2.0a) a command line option was introduced, to avoid above manually steps:

poetry add --editable /path/to/package

Another ways of adding packages can be found on poetry add page

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