The bigger your project grows, the more dependencies it has. Python offers a simple way to capture them and let everyone on your team install the exact same versions.
This post is part of my journey to learn Python. You can find the other parts of this series here.
Creating a package list
The command pip freeze shows you a list of all installed packages and their version. You can store this output in a file called requirements.txt and put it into version control:
1 |
pip freeze > requirements.txt |
You can check what list this command returns by calling pip freeze without pushing the output into the file:
1 2 3 4 5 6 |
(myenv) D:\Python_VirtualEnv>pip freeze appdirs==1.4.3 distlib==0.3.0 filelock==3.0.12 six==1.14.0 virtualenv==20.0.18 |
Installing the packages from that list
If you ship a requirements.txt with your project, your users can use the -r option and install the necessary dependencies from that file in their environment:
1 |
pip install -r requirements.txt |
More flexibility
If you use pip freeze you get a list of the exact version number of your dependencies. However, sometimes your program works with more versions than just this specific one. In this case you have multiple options to be less specific about your dependencies. The example requirements file in the documentation of pip has all the possibilities covered:
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 |
####### example-requirements.txt ####### # ###### Requirements without Version Specifiers ###### nose nose-cov beautifulsoup4 # ###### Requirements with Version Specifiers ###### # See https://www.python.org/dev/peps/pep-0440/#version-specifiers docopt == 0.6.1 # Version Matching. Must be version 0.6.1 keyring >= 4.1.1 # Minimum version 4.1.1 coverage != 3.5 # Version Exclusion. Anything except version 3.5 Mopidy-Dirble ~= 1.1 # Compatible release. Same as >= 1.1, == 1.* # ###### Refer to other requirements files ###### -r other-requirements.txt # # ###### A particular file ###### ./downloads/numpy-1.9.2-cp34-none-win32.whl http://wxpython.org/Phoenix/snapshot-builds/wxPython_Phoenix-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl # ###### Additional Requirements without Version Specifiers ###### # Same as 1st section, just here to show that you can put things in any order. rejected green # |
For even more details you can read PEP 440.
Conclusion
The requirements.txt is a simple way to track the dependencies of your project and share them with the users.
1 thought on “Python Friday #21: Manage Your Dependencies”