Python is a scripting language. It is hard to protect python code from being copied. No 100% protection is required but at least slow down those who have bad intentions. Is it possible to minify/uglify python code the way javascript front-end code is being done today?
EDIT: The python code will be used in Raspberry Pi, not server. On raspberry pi, anyone can take out the SDcard and gain access to the python code.
75 Answers
- What about starting off with only distributing the pyc files? These are files created by Python interpreter for performance reasons--their load times are faster than .pys--but to the casual user they are difficult to decipher.
python -m compileall .- Ramp up the security by using Cython to compile your python src. To "cythonize" your code, run Cython + GCC on each module. The init.py files must be left intact to keep module imports working. A silly Hello world example:
$ cython helloworld.py -o helloworld.c
$ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.7 -o helloworld.so helloworld.cYMMV using this approach; I've run into various gotchas using different modules.
I will answer my own question.
I found the following software tools that can do the job. I have not tried them, so I cannot comment on how effective they are. Comments are welcomed on their effectiveness.
4Sure, you could uglify it, but given the fact that python relies on indentation for syntax, you couldn't do the equivalent minification (which in JS relies largely upon removing all whitespace).
Beside the point, but JS is minified to make it download faster, not obfuscate it.
python is executed server-side. while sometimes it's fun to intentionally obfuscate code (look into perl obfuscation ;), it should never be necessary for server-side code.
if you're trying to hide your python from someone but they already have access to the directories and files it is stored in, you have bigger problems than code obfuscation.
1Nuitka.net is a perfect way to convert your python code to compiled object code. This makes reverse engineering and exposing your algorithms extremely hard. Nuitka can also produce an standalone executable that is very portable.
While this may be a way to preserve trade secrets, it comes with some hard limitations.
a) Some Python libraries are already binary distros which are difficult to bundle in a standalone exe (e.g. xgboost, pytorch).
b) wide pip distribution of a binary package is an exercise in deep frustration because it is linked to the CPython library. manylinux and universal builds are a vast wasteland waiting to be mapped and documented.
As for the downvotes, please consider that 1) not all python runs on servers - some run on the edge, 2) non-open source authors need to protect their intellectual property, 3) smaller always makes for faster installs.