DEV Community

Cover image for Best way to create requirements.txt
Sajidur Rahman Shajib
Sajidur Rahman Shajib

Posted on

Best way to create requirements.txt

Hello Devs,

How are you doing with Python?

In my previous post, I emphasized not using pip freeze to create requirements.txt but instead recommended using pip-tools. Today, I want to discuss another better approach to creating requirements.txt.

You might recall my earlier suggestion to create requirements.txt when you start your project. However, what do you do if you've already completed your project without generating requirements.txt?

requirements.txt is invaluable when you or someone else is trying to install all the project-related libraries and dependencies.

You can find my previous post here.

Main topic starts from here.

First, install pipreqs and pip-tools:

pip3 install pipreqs pip-tools
Enter fullscreen mode Exit fullscreen mode

Now, create requirements.in using pipreqs. Next, generate requirements.txt using pip-tools. But why do we combine these tools?

pipreqs doesn't capture sub-packages, which pip-tools does. So, we use pipreqs to create a package list in requirements.in. Then, we generate requirements.txt using pip-tools, where you'll find a comprehensive package list, including sub-packages.

Here is our final command:

pipreqs --savepath=requirements.in --use-local && pip-compile
Enter fullscreen mode Exit fullscreen mode

Both --savepath and --use-local are crucial parameters:

  • --savepath: Defines the exact filename and path for the requirements.in file.
  • --use-local: Retrieves the package list from your virtual environment.

So now you will find your desired requirements.txt

In this post, I haven't delved much into pip-tools. For a more detailed explanation, you can refer to my previous post about pip-tools.

Conclusion

Creating a requirements.txt file might not seem like a big issue, but sometimes it can be. I hope this post helps you cope with this issue. Feel free to comment if you have any questions or concerns.

Top comments (0)