Make Python go Vrooooom!

I’ve found myself in scenarios recently where I need to write portable apps & modules in Python, and disseminate them to varying devices. Through some very well crafted and quite elegant Google search queries, I came upon an interesting StackOverflow answer regarding Cython. The aforementioned answer covers how to (in Ubuntu) convert your Python file to a C file, and then compile it with gcc. While I am championing this method as a cool way to create efficient & portable modules to send off to your device fleet, there is some nuance to consider. In this article we’ll cover that so it’s very easy for you to manage expectations here.

Converting & Compiling

I typically like to use docker containers as miniature forges of sorts for building C code and compiling for specific environments. In my opinion it beats standing up VMs all the time, working strictly within the constraints of your bare-metal server or workstation and having to reconfigure your environment multiple times for varying compiles.

Below is a high level view of the conversion and compilation flow.

High-level flow of conversion and compilation of your Python file

Below screenshot video of me running the commands laid out in the aforementioned StackOverflow answer.

Screenshot video of converting and compiling from Python to C, and testing compiled binary file.

Requirements to Run

Requirements to run compiled code outside of compiled environment (remember, we’re talking about code that’s to be distributed):

  1. Ubuntu – This is a loose requirement, but all of my personal testing and has taken place with the newer versions of Ubuntu ( >= 16.04).
  2. libpythonX.X – This should reflect the version of python your compiling device uses. So if you’re compiled this with Python3.8 in Ubuntu you can install this with sudo apt-get install -y libpython3.8.
  3. All Python3 libraries that were imported in the original file. You can obtain these via pip install <package-name>, or building them from source.

Once all is said and done, I’d likely coalesce everything into a .deb file for easy install. But I need to stop the article here, as you can go so many places from here. So hopefully this was of some help to whomever may be reading. If you have any questions, feel free to hit up my contact page.