January 13, 2019
A non-programmer friend of mine asked me to help him write a script to automatically convert lab entries in a custom format into Excel spreadsheets. Sure! Just some text parsing and data cleaning with Pandas, then export the data as an Excel file - the job is done in 15 lines of Python code. 😃
However, it turns out that writing the code was only half of the work. Although my friend has Python installed as a part of his Linux distro, just copying the script without the dependencies wasn’t enough. Here we will be exploring 2 simple ways to package up Python scripts to distribute to people with less Python experiences!
requirements.txt file is a plain text file which contains all the dependency information. The format it uses is as simple as below:
# This is a comment pandas == 0.23.4 # Specify a dependency version
In order to get the specific version of the Pandas package, we can run
pip show pandas.
requirements.txt file along with the script itself, then your friend can simply run
pip install -r requirements.txt and all the dependencies will be installed automatically on their environment!
PyInstaller provides another even easier way to distribute our code. PyInstaller will automatically read the import statements in the script, find those packages in the current environment, then include those into the distribution. The end user doesn’t even need to have Python installed, because the binary contains the Python interpreter as well!
To use PyInstaller, first we’ll have to install the tools with
pip install pyinstaller. Then we will only have to run this single line of command
pyinstaller --onefile script.py. This will generate a huge single executable file based on the entry point
script.py, along with all the dependencies bundled right inside it.
Because PyInstaller actually bundles the interpreter into the executable as well, this method is not cross-platform like the
requirements.txt. So for example, if we want to create a Windows
.exe file, we will need to run PyInstaller on a Windows machine.