Sai Karthik

Balancing the braces ...

pip2poetry - A script to migrate from pip to poetry

February 26, 2023 | 2 minute read

I have recently learnt about Poetry, which is an advanced dependency management & packaging tool for python.

The features which i have found impressive is that, by default it installs the project’s dependencies in a seperate virtual environment. which is such a nice thing to have! and we can just activate the environment with command poetry shell. we can exit the virtual environment by exit command. This removes the need of a seperate virtual environment management software.

Also, Poetry makes it very easy to package & publishing the project to PyPi with commands poetry build & poetry publish respectively.

So, I tried to migrate the existing gkcore project, which uses pip & requirements file to manage it’s dependencies.

I first started the migration process. poetry init command converted the existing project into poetry project by adding two files pyproject.toml & poetry.lock file with initial data. Then, i searched if poetry can import dependencies from existing requirements.txt file & there seem to be no such built-in feature. So, i decided to write a simple script which does the job.

This script parses the requirements.txt file (optionally takes custom file name as first parameter) & then installs the packages using poetry command.

Download the script

Below is the contents of the file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import subprocess
from sys import argv as args


"""
pip2poetry - Import your requirements.txt into poetry

This script assumes that poetry is already installed

USAGE:
    python3 py2poetry.py <optional file path>
"""


pkg_file = "requirements.txt"


def main():
    # open the file containing the packages & read the contents
    with open(pkg_file) as f:
        file = f.readlines()
        # loop through all the lines
        for line in file:
            # ignore commented and blank lines
            if not line.startswith("#") and not line.isspace():
                # strip white spaces & spaces between words
                pkg = line.strip().replace(" ", "")
                # install the package with poetry
                try:
                    subprocess.run(["poetry", "add", pkg])
                except:
                    print(f"Failed to install {pkg}")


if len(args) == 2:
    pkg_file = args[1]
    main()
else:
    main()
Comment | Share

Tags: python pip