To compile and run a C code inside a Python script, we can make use of the subprocess
module in Python.
Here is an example of how it can be done
main.py191 chars8 lines
The subprocess.call
function takes a list of arguments as input. In the above example, we are passing the arguments to compile the C code using the GCC compiler and to run the compiled code.
The first argument gcc
is the name of the compiler, -o
is an option to specify the output file name, output_program
is the name of the compiled program, and input_program.c
is the name of the C code file to be compiled.
The second subprocess.call
function runs the compiled program by passing the name of the compiled executable file as an argument.
Note: The subprocess
module is available in Python 2 and 3, but the function names have been changed in Python 3. In Python 3, subprocess.call
has been replaced with subprocess.run
.
gistlibby LogSnag