Compile a C/C++ Program and store standard output

2019-09-21 05:20发布

问题:

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.

回答1:

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:

  1. I am hardcoding stuff. You may want to parameterize and all that.
  2. Setting shell to True, is a security risk, per Python documentation.


回答2:

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.