编译 C/C++ 程序并通过 Python 将标准输出存储在文件中

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

假设我有一个名为 userfile.c 的 C/C++ 文件。

使用Python,如何调用本地gcc编译器来编译文件并生成可执行文件?更具体地说,我想通过某个文件 input.txt 提供一些输入 (stdin),我想将标准输出保存到另一个名为 output.txt 的文件中。我看到了一些我需要使用子流程的文档,但我不确定如何调用它以及如何提供自定义输入。

一个简单的解决方案如下:

import subprocess

if subprocess.call(["gcc", "test.c"]) == 0:
    subprocess.call(["./a.out <input.txt >output.txt"], shell=True)
else: print "Compilation errors"

2 条注意事项:

  1. 我正在硬编码。您可能想要参数化等等。
  2. 根据 Python 文档,将 shell 设置为 True 存在安全风险。

这是一个可能的解决方案(为 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)

参数universal_newlines使得subprocess使用字符串而不是字节来输入和输出。如果您想要字节而不是字符串,请以二进制模式打开文件并设置 universal_newlines=False.

在两个程序中出现编译或 运行 错误时,subprocess.CalledProcessError 将由 subprocess.check_call 引发。