简体   繁体   中英

Passing stdin for cpp program using a Python script

I'm trying to write a python script which 1) Compiles a cpp file. 2) Reads a text file "Input.txt" which has to be fed to the cpp file. 3) Compare the output with "Output.txt" file and Print "Pass" if all test cases have passed successfully else print "Fail". `

 import subprocess
 from subprocess import PIPE
 from subprocess import Popen
 subprocess.call(["g++", "eg.cpp"])
 inputFile = open("input.txt",'r')
 s = inputFile.readlines()
 for i in s :
     proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
     out = proc.communicate()
     print(out)

`

For the above code, I'm getting an output like this,

(b'32769', None)
(b'32767', None)
(b'32768', None)
Traceback (most recent call last):
  File "/home/zanark/PycharmProjects/TestCase/subprocessEg.py", line 23, in <module>
    proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
ValueError: invalid literal for int() with base 10: '\n'

PS :- eg.cpp contains code to increment the number from the "Input.txt" by 2.

pass the string to communicate instead, and open your file as binary (else python 3 won't like it / you'll have to encode your string as bytes ):

 with open("input.txt",'rb') as input_file:
    for i in input_file:
     print("Feeding {} to program".format(i.decode("ascii").strip())
     proc = Popen("./a.out", stdin=PIPE, stdout=PIPE)
     out,err = proc.communicate(input=i)
     print(out)

also don't convert input of the file to integer. Leave it as string (I suspect you'll have to filter out blank lines, though)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM