4

I have a Python package for scientific work that, as part of it, runs an executable (via subprocess) that is compiled from a single C source file, and is otherwise unrelated to Python (ie, it isn't an extension).

We'd like to include the C source in the package, such that setup.py (we are using setuptools) will compile it and the package can access the executable, either via pkg_resources or by installing it in the user's path along with scripts generated by console_scripts.

Is there a way we can do this? For maintainability reasons, we'd prefer not to convert the executable to a C extension, and having the command available is somewhat useful to our users anyway.

cge
  • 9,552
  • 3
  • 32
  • 51
  • Check out https://stackoverflow.com/questions/33168482/compiling-installing-c-executable-using-pythons-setuptools-setup-py if you are still wondering how to do this, as well as https://stackoverflow.com/a/36902139/4174466 which gives a clearer example of post-install commands. Including the source file in your MANIFEST.in, as well as using the "data_files" to include the compiled executable worked for me – Scott Staniewicz Jun 14 '18 at 17:01

1 Answers1

0

You pretty much answered your own question. What's stopping you from doing what you just described there, and creating a setup.py file that will look something like the snippet below.

import subprocess
from distutils.core import setup

code = """
#include <stdio.h>
int main(int argc, char *argv[]){printf("%s\\n", "Hello world.");}
"""

# Write code to file 
f = open("main.c", 'w')
f.write(code)
f.close()

# Compile c code
p = subprocess.Popen(["cc", "-O2", "main.c", "-o", "main.out"]).wait()
subprocess.call(["./main.out"])

setup(name='foobar',
      version='1.0',
      packages=['foobar', 'foobar.subfoo'],
      )
Boris
  • 2,275
  • 20
  • 21