6 Things I Wish I Knew Earlier About requirements.txt

<h1>1) How to install everything inside requirements.txt</h1> <p><code>requirements.txt</code>&nbsp;contains the required libraries for a project that needs to be installed (usually using pip). A simple example:</p> <pre> library-one==1.0.1 library-two==3.1.4 library-three==100.1.0</pre> <p>To install all 3 libraries, we can run the command:</p> <pre> pip install -r requirements.txt</pre> <p>which will install every single line inside&nbsp;<code>requirements.txt</code></p> <h1>2) How to generate requirements.txt</h1> <pre> pip freeze</pre> <p>This command prints out in the terminal 1) every external module you have installed in whatever Python you are using 2) their exact versions. Something like this will print in the terminal (truncated):</p> <pre> absl-py==1.4.0 altair==5.0.1 anyio==3.6.2 appdirs==1.4.4 appnope==0.1.3 argon2-cffi==21.3.0</pre> <p>This is essentially the stuff inside a&nbsp;<code>requirements.txt</code>&nbsp;file. Since we want these lines in a text file, but don&rsquo;t want to manually copy paste it, let&rsquo;s use the following command to write it to a file.</p> <pre> pip freeze &gt; requirements.txt</pre> <p>^ whatever output from&nbsp;<code>pip freeze</code>&nbsp;will be written to a text file with the name&nbsp;<code>requirements.txt</code>. And there we have it &mdash; how to generate a&nbsp;<code>requirements.txt</code>&nbsp;file!</p> <h1>3) It is better to use a Python virtual environment to create a requirements.txt</h1> <p>When we&nbsp;<code>pip freeze</code>, EVERY SINGLE installed library will appear in your&nbsp;<code>requirements.txt</code>. Which can get annoying &mdash; what if your project simply needs&nbsp;<code>numpy</code>&nbsp;and&nbsp;<code>pandas</code>, but&nbsp;<code>requirements.txt</code>&nbsp;will install another 100 unnecessary libraries.</p> <p>When we use a Python virtual environment, we create a new instance of Python that is separate from your main Python.</p> <p><a href="https://levelup.gitconnected.com/6-things-i-wish-i-knew-earlier-about-requirements-txt-1f89b689f362">Read More</a></p>
Tags: Code Python