Let's say I have a C/C++ file named userfile.c
.
Using Python, how can I invoke the local gcc compiler so that the file is compiled and an executable is made? More specifically, I would like to provide some input (stdin) via some file input.txt
and I want to save the standard output into another file called output.txt
. I saw some documentation that I will need to use subprocess, but I'm not sure how to call that and how to provide custom input.
A simple solution will be as given below:
import subprocess
if subprocess.call(["gcc", "test.c"]) == 0:
subprocess.call(["./a.out <input.txt >output.txt"], shell=True)
else: print "Compilation errors"
2 caveats:
- I am hardcoding stuff. You may want to parameterize and all that.
- Setting shell to True, is a security risk, per Python documentation.
Here's a possible solution (written for Python 3):
import subprocess
subprocess.check_call(
('gcc', '-O', 'a.out', 'userfile.c'),
stdin=subprocess.DEVNULL)
with open('input.txt') as infile, open('output.txt', 'w') as outfile:
subprocess.check_call(
('./a.out',),
stdin=infile,
stdout=outfile,
universal_newlines=True)
The parameter universal_newlines
makes subprocess
use strings rather than bytes for input and output. If you want bytes rather than strings, open the files in binary mode and set universal_newlines=False
.
On compile or run errors in the two programs, subprocess.CalledProcessError
will be raised by subprocess.check_call
.