为了账号安全,请及时绑定邮箱和手机立即绑定

python子进程运行c++任务读取文件错误

python子进程运行c++任务读取文件错误

ITMISS 2023-12-12 15:06:56
我有一个读取文件并处理它的 C++ 任务:// 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    }我有一个 python 脚本来设置测试数据并运行任务:import unittest   def test_A():       file='myfile.txt'       with open(file, 'w') as filetowrite:           filetowrite('testdata')       subprocess.run(["A.tsk"])但是,当我运行 python 脚本并执行 c++ 任务时,第一个 while 循环有效,但 for 循环只是在此处中断 eof 的 bc :for(;;){       file.getline(buffer); // buffer is "testdata"       if (file.eof()) break;  // it breaks even buffer is "testdata"      // process some other logic    }我打印了buffer它,它有“testdata”,但是它只是在下一行中断,所以它没有得到处理,这不是我想要的。但是,如果我不使用 pythonsubprocess运行它,也不使用 Python 设置测试数据,而只是手动echo testdata >> myfile.txt编译A.m.cpp和运行A.tsk,则它不会中断 for 循环并成功处理“testdata”。出什么问题了subprocess?为什么有内容eof也会触发?buffer
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

您应该在处理后放置 .eof() 中断:

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

即使在读取数据后遇到 EOF,您也需要处理数据。请注意,这可能会在缓冲区中提供空字符串,因此您可能需要在处理代码中处理这种情况。

您还需要将 python 行更改为:

filetowrite.write("testdata\n")


查看完整回答
反对 回复 2023-12-12
  • 1 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信