Open In App

Script management with Python Poetry

Last Updated : 07 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Poetry is a tool that makes it easier to manage Python dependencies and packages and create virtual environments for a project, as well as to package and distribute Python libraries. Apart from dependency management, script management is also one of the strong features of Poetry where developers can define and run scripts in their projects easily. In this article, you will learn the following about how to work with scripts when using Poetry, Setting up and configuring scripts in Python projects, and using scripts with Poetry.

Introduction to Script Management with Poetry

Script management in Python projects is the process of creating script definitions, and maintaining and executing scripts for tasks like testing building, and deployment. It does this by enabling you to define scripts in the pyproject.toml file within your project, thereby allowing you to run these scripts within your project easily and without introducing a lot of changes to your environment.

Setting Up Poetry

Poetry provides such tools also, which automatically define as well as maintain virtual environments for your respective projects. Here's how you can get started:

Install Poetry

use the following command on the terminal to install poetry:

pip install poetry
poetry

Initialize a New Project

Create a new project directory and initialize it with Poetry.

mkdir my_project
cd my_project

Run poetry init

Use the poetry init command to start the interactive setup for your pyproject.toml file:

poetry init

Follow the Prompts

This shall give you fields that require some input about your project. Below is an example:

tutorial
project setup prompts

Defining Custom Scripts

The scripts can be defined in the tool. poetry. in the scripts section of your pyproject. toml file. This section enables the reader to associate the script names to Python functions or shell commands.

Example Configuration

Below is an example of how to configure the pyproject.toml file for using custom scripts:

[tool.poetry]
name = "my_project"
version = "0.1.0"
description = "A short description of my project"
authors = ["Your Name <[email protected]>"]

[tool.poetry.scripts]
say_hello = "my_project.scripts:say_hello"
run_server = "my_project.scripts:run_server"

In this example, two scripts are defined:

  • say_hello: A script that runs the say_hello function from the my_project.scripts module.
  • run_server: A script that runs the run_server function from the my_project.scripts module.

Implementing the Scripts

Create a scripts.py file in your project's module directory (my_project/scripts.py) and define the corresponding functions:

Python
# my_project/scripts.py

def say_hello():
    print("Hello, world!")

def run_server():
    import http.server
    import socketserver

    PORT = 8000
    Handler = http.server.SimpleHTTPRequestHandler

    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"Serving at port {PORT}")
        httpd.serve_forever()

Running Scripts with Poetry

As mentioned earlier, the scripts are defined in the pyproject. To run the actions that you have specified in the TOML and implemented in your code, you can use the Poetry CLI.

Running a Script

To run a script, use the poetry run command followed by the script name:

poetry run say_hello
hello

This command will execute the say_hello script, outputting "Hello, world!" to the console.

Running the Server Script

Similarly, you can run the server script:

poetry run run_server

This command will start the HTTP server and serve files from the current directory on port 8000.

8000
http://localhost:8000

Using Environment Variables

You can pass environment variables to your scripts by setting them in your shell before running the script:

export MY_VARIABLE=value
poetry run my_script

Chaining Scripts

You can chain multiple scripts together using shell commands or by defining composite scripts in your pyproject.toml file:

[tool.poetry.scripts]
build_and_test = "sh -c 'poetry run build && poetry run test'"

Defining Default Scripts

You can define a default script to run when no specific script is provided by using the tool.poetry.scripts section:

[tool.poetry.scripts]
default = "my_project.scripts:default_function"

Now, running poetry run without any arguments will execute the default_function script.

Script Usage and Documentation

It is critical to ensure that your scripts are documented well in order to have a well structured project. When other developers (and that could be you in a few months) will look at your scripts, they will be able to understand what these scripts are used for, how they should be used, and if any arguments or environment variables are expected.

Documenting Scripts in pyproject. toml

It is also possible to include comments in the pyproject file, so that you can include additional information if you need to provide context and usage information for your scripts.

[tool.poetry.scripts]
# Prints "Hello, world!" to the console
say_hello = "my_project.scripts:say_hello"

# Starts a simple HTTP server on port 8000
run_server = "my_project.scripts:run_server"

Providing Inline Documentation in Scripts

Add docstrings to your Python functions to describe what each script does, the arguments it accepts, and any other relevant information:

Python
# my_project/scripts.py

def say_hello():
    """
    Prints 'Hello, world!' to the console.
    """
    print("Hello, world!")

def run_server():
    """
    Starts a simple HTTP server on port 8000.

    This server serves files from the current directory.
    """
    import http.server
    import socketserver

    PORT = 8000
    Handler = http.server.SimpleHTTPRequestHandler

    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"Serving at port {PORT}")
        httpd.serve_forever()

Creating a README File

Include a README file in your project root that provides an overview of your scripts, including how to run them and any prerequisites:

# My Project

## Scripts

### `say_hello`

Prints "Hello, world!" to the console.

```sh
poetry run say_hello

Next Article
Article Tags :
Practice Tags :

Similar Reads