Script management with Python Poetry
Last Updated :
07 Jun, 2024
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

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:
project setup promptsDefining 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

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.
http://localhost:8000Using 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
Similar Reads
Using Poetry Dependency Management tool in Python
In this article, we are going to study the poetry dependency management tool in python which will help you to manage the libraries of your next project so it will be easy to download, install, and set up your project. What is Poetry Poetry is a python dependency management tool to manage dependencie
4 min read
Managing dependencies with Python Poetry
Managing dependencies in Python projects can be a challenging task, especially as projects grow in size and complexity. Poetry is a powerful tool designed to simplify dependency management, packaging, and publishing for Python projects. In this article, weâll explore what Poetry is, its features, an
3 min read
Python - Making a Reddit bot with PRAW
Reddit is a network of communities based on peopleâs interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them. A Reddit bot is something that automatically responds to a userâs post or automatically posts things at
2 min read
Conda vs Poetry in Python
When it comes to managing Python environments and dependencies, two tools often stand out: Conda and Poetry. Each has its strengths and specific use cases, catering to different needs within the Python development community. This article explores the key features, advantages, and differences between
4 min read
How to Run a Python Script
Python scripts are Python code files saved with a .py extension. You can run these files on any device if it has Python installed on it. They are very versatile programs and can perform a variety of tasks like data analysis, web development, etc. You might get these Python scripts if you are a begin
6 min read
Getting Started with Python Programming
Python is a versatile, interpreted programming language celebrated for its simplicity and readability. This guide will walk us through installing Python, running first program and exploring interactive codingâall essential steps for beginners.Install PythonBefore starting this Python course first, y
3 min read
Making a text object with VPython
VPython makes it easy to create navigable 3D displays and animations, even for those with limited programming experience. Because it is based on Python, it also has much to offer for experienced programmers and researchers. VPython allows users to create objects such as spheres and cones in 3D space
4 min read
Publishing packages with Poetry
Poetry has revolutionized the way Python developers manage their dependencies and publish their packages. Its simple, intuitive, and powerful interface streamlines the process of creating and maintaining Python projects. This article provides a comprehensive guide on how to publish packages using Po
3 min read
Managing Project Metadata in Python Poetry
Managing project metadata efficiently is crucial for the success of any software project. Python Poetry, a popular dependency management tool, simplifies this process, making it easier to handle project configurations. This article will guide you through managing project metadata in Python Poetry, c
3 min read
How to Build and Publish Python Packages With Poetry
Poetry is a modern and useful tool for package development and distribution in Python that helps with dependency management. The entire process is consolidated into a single, intuitive interface with Poetry, in contrast to conventional methods that call for numerous tools and intricate setups. This
6 min read