poetry has a scripts feature like Pipenv, but what you type like npm scripts doesn't just run in the shell. Only functions with no arguments can be executed.
For details, please refer to the following link because there is an article I wrote before. [Python] I started Poetry & Impressions of transition from Pipenv to poetry
This time I'll write a simple script so that I can launch the Django development server with a single command.
The directory after doing $ django-admin startproject config .
after $ poetry install
.
Write the file for poetry scripts in ./scripts
. This time it is for server startup, so I chose server.py
.
.
├── config
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── poetry.lock
├── pyproject.toml
└── scripts
└── server.py
script
Created with the following contents.
At first, I specified manage.py
with an absolute path, but it worked even if it wasn't.
scripts/server.py
import subprocess
def main():
cmd = ["python", "manage.py", "runserver", "0.0.0.0:8000"]
subprocess.run(cmd)
pyproject.toml
Add the following:
pyproject.toml
[tool.poetry.scripts]
start = 'scripts.server:main'
This alone will result in [ModuleOrPackageNotFound] No file / folder found for package <project name>
.
$ poetry run start
[ModuleOrPackageNotFound]
No file/folder found for package project
If the scripts file is under the root directory (the directory where pyproject.toml is) You need to specify the package directory.
pyproject.toml
[tool.poetry]
name = "project"
version = "0.1.0"
description = ""
authors = [""]
packages = [
{ include="scripts", from="." },
]
Now you can start it. Even if you execute it from a shell that is not in the virtual environment, it will be executed in the virtual environment.
$ poetry run start
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
February 14, 2020 - 10:41:57
Django version 3.0.3, using settings 'config.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
...
The poetry script executed in this way must be executed in the directory containing pyproject.toml.
Poetry can't find the scripts
directory because it saysfrom = "."
.
pyproject.toml
packages = [
{ include="scripts", from="." },
]