Skip to content

Instantly share code, notes, and snippets.

@0xFF1E071F
Forked from itdaniher/compile.py
Created October 26, 2020 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xFF1E071F/87184609d8551ccdab0ef1c122f1c3dc to your computer and use it in GitHub Desktop.
Save 0xFF1E071F/87184609d8551ccdab0ef1c122f1c3dc to your computer and use it in GitHub Desktop.
compile python script to ELF on Linux via cython and gcc
import subprocess
import sys
import tempfile
from Cython.Compiler import Main, CmdLine, Options
in_file_name = sys.argv[1]
source = open(in_file_name).read()
out_file_name = in_file_name.replace('.py', '.out')
temp_py_file = tempfile.NamedTemporaryFile(suffix='.py', delete=False)
temp_py_file.write(source.encode())
temp_py_file.flush()
Main.Options.embed = 'main'
res = Main.compile_single(temp_py_file.name, Main.CompilationOptions(), '')
gcc_cmd = 'gcc -fPIC -O2 %s -I/usr/include/python3.8 -L/usr/lib/python3.8 -lpython3.8 -o %s' % (res.c_file, out_file_name)
print(gcc_cmd)
assert 0 == subprocess.check_call(gcc_cmd.split(' '))
@0xFF1E071F
Copy link
Author

Above code tested on Arch Linux. I have written a hello world py and can easily converted to out file. 64-bit elf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment