Skip to main content
 首页 » 编程设计

python之如何为 SCons 指定标准输入文件

2024年10月24日10mq0036

我有一个 C 程序“add.c”,一个输入文件“input.txt”。我希望使用 SCons 编译这个程序并将标准输出存储到一个名为“output.txt”的文件中。如何使用 SCons 构建实用程序实现此目的?我怎样才能制作一个 python 脚本来完成这项工作?

compute(input_source_code,input_file_for_input_source_code) {//generate output file} 

我阅读了 SCons 的文档,它谈到了多个输入源文件,但我无法理解如何为编译的源文件指定输入(标准输入)。

进一步澄清 - 我正在尝试使用 Python/Django 构建在线作业评分器。我希望为此特定任务完成的是: 编译给定的 C 程序——为所有 C 程序提供一些预定义的输入,然后将执行 C 程序生成的输出存储到另一个文件中。如果我理解正确,SCons 允许我构建/制作 C 程序文件,但我如何指示 SCons 从特定文件获取特定 C 程序的输入。那就是我尝试通过 SCons 构建的 C 程序应该从特定文件获取输入。

Compile a C/C++ Program and store standard output in a File via Python Sam Noir 在这里的回答之一解决了我的问题,但它仅适用于 Mac/Linux 但不适用于 Windows - 这就是我尝试使用 SCons 构建实用程序来完成此任务的原因。

只是想我可以添加一个示例:

C文件(add.c)

#include <stdio.h> 
int main() 
{ 
int a,b; 
scanf("%d", &a); 
scanf("%d", &b); 
printf("%d", a+b); 
return 0; 
} 

输入.txt:

3 7 

Python 脚本:

BUILD(add.c - fetch the required input from input.txt) and  
store the output into another file output.txt  

(因此它应该在 output.txt 中打印 10)。

所以基本上我想使用 SCons 来构建和运行文件 add.c 并通过确保从 input.txt 中获取 add.c 所需的任何输入来生成 output.txt。

请您参考如下方法:

对于您给出的示例,您可以尝试类似的操作:

env = Environment() 
# Build the program and store a reference to it 
prog = env.Program("cl_add", "add.c") 
# Create a Command to run, relies on shell redirection 
out = env.Command('output.txt','input.txt','%s < $SOURCE > $TARGET' % str(prog[0])) 
# Let the Command depend on the Program created above 
env.Depends(out, prog) 

在你的 SConstruct 中。另请参阅 http://scons.org/doc/production/HTML/scons-user.html 处的用户指南, 第一章19.“不编写生成器:命令生成器”。