1

Check.cpp

int main(int argc, char** argv)
{
    string file = "";
    ifstream inFile;
    int x;
    file = argv[1];
    inFile.open(file.c_str());
    while (inFile >> x)
        cout << x << endl;
    return 0;
}

Print.py

from __future__ import with_statement
from shutil import copy
import subprocess
import filecmp
import sys

count = 0
f = open ("filename.txt","r")
file1 = open ("file1.txt","w") 
file2 = open ("file2.txt","w")
file3 = open("out1.txt","w")
file4 = open("out2.txt","w")

for line in range(1,2):
    firstline = f.readline()
    file1.write(firstline)
    subprocess.Popen(["./a.out","file1.txt"],stdout=file3)
    file2.write(firstline)
    subprocess.Popen(["./a.out","file2.txt"],stdout=file4)
    if (filecmp.cmp('out1.txt', 'out2.txt') == True):
        count = count + 1

print count

Input:

filename.txt:
    123 
    234
    456

Output:

file1.txt:
    123

file2.txt:
    123

out1.txt:
    Expected Output - 123. But no output is returned

out2.txt
    Expected Output - 123. But no output is returned

I am trying to run the simple C++ program through Python script. I tried subprocess.Popen(), subprocess.call(), subprocess.check_output(). But none of them redirecting the command line output to file.

James Z
  • 12,209
  • 10
  • 24
  • 44
kumar_123
  • 11
  • 3
  • 2
    Post your whole code please, not just some lines. Are you closing your file? – Selcuk May 01 '18 at 04:54
  • What happens when you run `./a.out 0-9 file.txt 2>/dev/null` in the terminal? – abarnert May 01 '18 at 04:55
  • @Selcuk I added my entire code as you asked. The only problem is with subprocess.Popen(). – kumar_123 May 01 '18 at 05:10
  • 1
    @abarnert Program successfully prints the output in the terminal. – kumar_123 May 01 '18 at 05:11
  • You're trying to `filecmp.cmp` the files, without first closing (or at least flushing) them. So, the output may well still be buffered. You could have nothing, or the whole thing, or just `1`. Since you're going to the trouble of `from __future__ import with_statement`, why not use some `with` statements here? – abarnert May 01 '18 at 05:14
  • You need to use `subprocess.call()` or call `wait()` on the return value of Popen. – jordanm May 01 '18 at 05:25

0 Answers0