重定向输入Python [英] Redirecting input Python

查看:275
本文介绍了重定向输入Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 inputfile.write( 47); 
cmd = [gcc, - 02,srcname, - o,execname];
p = subprocess.Popen(cmd,stderr = errfile);
errfile.close();
#print(p)
p.wait();
...
subprocess.call([./\"+ execname],stdin = inputfile,stdout = outputfile)





以上是我使用Python编译C程序的代码的一部分。



srcname是输入.c文件名

execname是C可执行文件名



subprocess.Popen(cmd,stderr = errfile); //这是编译我的C程序并在errfile中打印错误



subprocess.call([./+ execname],stdin = inputfile,stdout = outputfile )//这是在编译成功的情况下执行我的C文件



以下是我在名为srcname的文件中的C源代码:



 #include< stdio.h> 
int main(int argc,char * argv [])
{
int n;
scanf(%d,& n);
printf(%d,n);
}





我的输入文件包含47(参见第一行)。但是输出文件总是包含14.





使用下面的命令行参数,我在输出文件中输出正确。



C:/ gcc srcname.c

C:/a.exe< input.txt> output.txt

解决方案

 inputfile.write(  47< /跨度>); 
inputfile.flush();
cmd = [ gcc - O2,srcname, - o,execname];
p = subprocess.Popen(cmd,stderr = errfile);
errfile.close();
print(p)
p.wait();
...
subprocess.call([ ./ + execname ],标准输入= inputfile中,由于输出= OUTPUTFILE)


inputfile.write("47");
cmd = ["gcc", "-O2", srcname, "-o", execname];
p = subprocess.Popen(cmd,stderr=errfile);
errfile.close();
#print(p)
p.wait();
...
subprocess.call(["./"+execname],stdin=inputfile,stdout=outputfile)



Above is some portion of my code to compile a C program using Python.

srcname is the input .c filename
execname is the C Executable filename

subprocess.Popen(cmd,stderr=errfile); // This is compiling my C program and printing the errors in errfile

subprocess.call(["./"+execname],stdin=inputfile,stdout=outputfile)// This is executing my C file on the condition that compilation is succesful

Below is my C source code in the file named srcname:

#include <stdio.h>
int main(int argc, char *argv[])
{
int n;
scanf("%d",&n);
printf("%d",n);
}



My inputfile contains 47 (refer first line). But the outputfile always contains 14.


using the below command line argument, I am getting right output in the output file.

C:/gcc srcname.c
C:/a.exe<input.txt>output.txt

解决方案

inputfile.write("47");
inputfile.flush();
cmd = ["gcc", "-O2", srcname, "-o", execname];
p = subprocess.Popen(cmd,stderr=errfile);
errfile.close();
#print(p)
p.wait();
...
subprocess.call(["./"+execname],stdin=inputfile,stdout=outputfile)


这篇关于重定向输入Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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