Compile a C/C++ Program and store standard output in a File via Python

与世无争的帅哥 提交于 2019-12-14 03:36:21

问题


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.



来源:https://stackoverflow.com/questions/33240011/compile-a-c-c-program-and-store-standard-output-in-a-file-via-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!