Search code examples
pythonbytecode

Is byte-compiling Python platform-specific?


I want to byte-compile a python library I use on an embedded device.

Basically, I want to preprocess all *.py files to __pycache__/*.pyc files to avoid that happening the first time this app is used and slowing everything down.

I'm trying to understand if this pre bytecode-translation step has any dependency on the place in which it run (my laptop vs another device). If I byte-compile my python app with compileall on an Ubuntu box (x86-based) and then take those bytecode-translated files that get placed in a __pycache__ directory to an embedded linux box (ARM-based), will they work? Is byte-compiling platform specific?

I'm less concerned about whether .pyc files are compatible with different versions of python as much as different underlying architectures. Both my machine and the device use python3.4.


Solution

  • If I byte-compile my python app [...] on an Ubuntu box (x86-based) and then take those bytecode-translated files [...] to an embedded linux box (ARM-based), will they work?

    Assuming that the interpreter version uses a compatible bytecode form (only changed when major or minor version numbers differ), yes, they will work.

    Quoting from an excellent answer to a related question by John La Rooy:

    # python:  file(1) magic for python
    0   string      """ a python script text executable
    0   belong      0x994e0d0a  python 1.5/1.6 byte-compiled
    0   belong      0x87c60d0a  python 2.0 byte-compiled
    0   belong      0x2aeb0d0a  python 2.1 byte-compiled
    0   belong      0x2ded0d0a  python 2.2 byte-compiled
    0   belong      0x3bf20d0a  python 2.3 byte-compiled
    0   belong      0x6df20d0a  python 2.4 byte-compiled
    0   belong      0xb3f20d0a  python 2.5 byte-compiled
    0   belong      0xd1f20d0a  python 2.6 byte-compiled
    

    ...if your platforms use a compatible enough version to share the same magic, the .pyc files will work between them.