简体   繁体   中英

python subprocess running c++ task reading file error

I have a c++ task which reads a file and process it:

// A.m.cpp
    std::string filename = "myfile.txt";
    std::ifstream file(filename.c_str());
    std::ifstream file1(filename.c_str());
    std::string line1;
    while(getline(file1, line1)){
      // process some logic 
    }
    
    for(;;){
       file.getline(buffer);
       if (file.eof()) break;
      // process some other logic
    }

and I have a python script to set test data and run the task:

import unittest
   def test_A():
       file='myfile.txt'
       with open(file, 'w') as filetowrite:
           filetowrite('testdata')

       subprocess.run(["A.tsk"])

However, when I run the python script and executing the c++ task, the first while loop works, but the for loop just break bc of eof here:

for(;;){
       file.getline(buffer); // buffer is "testdata"
       if (file.eof()) break;  // it breaks even buffer is "testdata"
      // process some other logic
    }

I printed buffer and it has "testdata", however it just breaks in the next line so it did not got processed which is not what i want. However, if i do not use python subprocess to run it nor use Python to set test data, and just echo testdata >> myfile.txt , then compile Amcpp and run A.tsk manually, it did not break in the for loop and process "testdata" successfully. What is wrong with subprocess ? Why does it trigger eof even buffer has content?

You should put the .eof() break after the processing:

for(;;){
    file.getline(buffer); // buffer is "testdata"
    // process some other logic
    if (file.eof()) break;
}

You'll want to process the data even if EOF is hit after it's read. Note that this can give you empty strings in buffer, so you might want to handle that case in the processing code.

You'll also want to change the python line to:

filetowrite.write("testdata\n")

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