编译C/C ++程序并通过Python将标准输出存储在文件中 [英] Compile a C/C++ Program and store standard output in a File via Python

查看:237
本文介绍了编译C/C ++程序并通过Python将标准输出存储在文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a C/C++ file named userfile.c.

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

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个警告:

  1. 我正在硬编码东西.您可能要参数化所有这些内容.
  2. 根据Python文档,
  3. shell 设置为 True 是安全隐患.
  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.

这篇关于编译C/C ++程序并通过Python将标准输出存储在文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆