Skip to content

Instantly share code, notes, and snippets.

@maedoc
Created June 12, 2017 09:26
Show Gist options
  • Save maedoc/038ce57f14631721d4876a6b7b99cba1 to your computer and use it in GitHub Desktop.
Save maedoc/038ce57f14631721d4876a6b7b99cba1 to your computer and use it in GitHub Desktop.
First shot at Cythonizing a whole Python source tree...
import os
import sys
import subprocess
# gcc $(python3-config --cflags) -fPIC -c $file
# gcc -shared $(python3-config --ldflags) utils.o -o utils.so
def flags():
proc = subprocess.Popen(['python3-config', '--cflags'], stdout=subprocess.PIPE)
cflags = proc.stdout.read().decode('ascii')
proc = subprocess.Popen(['python3-config', '--ldflags'], stdout=subprocess.PIPE)
ldflags = proc.stdout.read().decode('ascii')
return cflags, ldflags
def filenames():
for root, _, filenames in os.walk(sys.argv[1]):
for filename in filenames:
if filename.endswith('.py') and not filename[0] == '_':
yield root, filename
def process(root, filename):
cflags, ldflags = flags()
subprocess.check_call(['cython', os.path.join(root, filename)])
subprocess.check_call(
['gcc'] + cflags.split() + ['-fPIC', '-c', filename.replace('.py', '.c')],
cwd=root)
subprocess.check_call(
['gcc', '-shared'] + ldflags.split() + [
filename.replace('.py', '.o'),
'-o',
filename.replace('.py', '.so')],
cwd=root)
if __name__ == '__main__':
for root, filename in filenames():
process(root, filename)
print(root, filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment