Obfuscating Python code

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Mar 16 03:04:10 EDT 2016


On Wednesday 16 March 2016 05:59, Thomas 'PointedEars' Lahn wrote:

> On a more constructive note, python(1) (CPython) creates a binary (byte-
> code) “.pyc” file from “.py” files when it runs them.  

To be precise, it creates a .pyc file when the file is imported, not run. 
Just running a Python script doesn't save the byte-code into a file.


> ISTM that you can
> then run the “.pyc” file as if it were the “.py” file 

Correct. You can compile the file, delete or move the source code, then run 
the .pyc file:

steve at runes:~$ cat test.py 
print("Hello World!")
steve at runes:~$ python2.7 -m compileall test.py 
Compiling test.py ...
steve at runes:~$ mv test.py test~
steve at runes:~$ python2.7 test.pyc 
Hello World!


However byte-code is version-specific: you can only run the .pyc file with 
the same version of the interpreter as the one you compiled it with:

steve at runes:~$ python2.6 test.pyc 
RuntimeError: Bad magic number in .pyc file


> (if the “.pyc” file
> is given the executable flag, you can even execute it as a standalone
> command, but that might only work on my system).

There may be ways to get it to work, but it doesn't work here:

steve at runes:~$ chmod a+x test.pyc 
steve at runes:~$ ./test.pyc 
: command not found 
./test.pyc: line 2: syntax error near unexpected token `('
./test.pyc: line 2: `$�Vc@s	dGHdS(s
                                         Hello 
World!N((((stest.py<module>s'



> So apparently you do not have to
> distribute the source code of a program written in Python if you do not
> want to.

Correct. This is a deliberate feature, intentionally supported by the Python 
interpreter.




-- 
Steve




More information about the Python-list mailing list