OneRaynyDay
OneRaynyDay

Reputation: 3968

Invoke g++/clang from python to compile a python string

I am currently writing an application that generates C++ code into a python string. I want to compile this code and create a .so from it.

The easiest way is to write the python string containing the code into a file, and use subprocess.Popen(...) to invoke g++/clang to compile it into a .so, but I would rather not write the string to disk first and have that as an intermediate step.

I have looked online for g++/clang bindings in python, and they were all simply parsers(for example, libclang), and do not actually compile anything.

Is there an alternative method that I'm missing here? Or do I need to bite the bullet and use subprocess?

Upvotes: 1

Views: 874

Answers (1)

PaulR
PaulR

Reputation: 3717

Mat's comment in python3 using the input argument of subprocess.run

This uses the fact that g++ accepts code from standard input when passed the file name -. Because there is no file name suffix, the compiler cannot guess the language, so it should be specified with -x.

The encoding argument was added to make the input argument accept a string, otherwise it expects a bytes-like object.

#!/usr/bin/python3

import subprocess
import locale

def compile_cpp(cpp_code_as_string, exe_name):
    command = ('g++', '-xc++', '-', '-o', exe_name)
    subprocess.run(command, input=cpp_code_as_string, encoding=locale.getpreferredencoding())

hello = '''
#include <iostream>

int main() {
  std::cout << "Hello World!\\n";
  return 0;
}
'''

compile_cpp(hello, 'hello')
subprocess.run(['./hello'])

Upvotes: 4

Related Questions