描述

在同一电脑下,有一个python程序,还有一个C++程序。通过一种比较投机取巧的方法完成进程间通信。就是python和C++读写txt的方式

代码

python端

import os
import time

def writePose(path, pose):
	with open(path, "w") as f:
		for i in range(6):
			f.write(str(pose[i])+"\n")

def readPose(path):
	while(True):
		if os.access(path, os.F_OK):
			print("cpp data path exists")
			break
		else:
			print("no cpp data path")
			time.sleep(1)
	pose = [0.0]*6
	i = 0
	with open(path, "r") as f:  # 打开文件
		for line in f.readlines():
			line = line.strip('\n')  #去掉列表中每一个元素的换行符
			pose[i] = float(line)
			i = i + 1

	return pose


pose = [1.124518745, 1.3, 1.0, 1.0, 1.0, 1.0]
writePose("pythonWrite.txt", pose)

pose1 = readPose("cppWrite.txt")
print(pose1)

C++端

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <unistd.h>

std::vector<double> readRobotPose(std::string path)
{
    std::ifstream robotPosefile; 
    robotPosefile.open(path.data());   //将文件流对象与文件连接起来 
    
    while(robotPosefile.is_open()!= 1)
    { 
        std::cout<<"no Robot Pose data"<<std::endl;
        sleep(1);
    }
    
    std::string content;
    int line = 0;
    std::vector<double> pose;
    while(getline(robotPosefile,content))
    {
        double p = atof(content.c_str());
        pose.push_back(p);
        line++;
    }
    std::cout<<"data has "<<line<<" lines"<<std::endl;
    robotPosefile.close(); 
    return pose;
}

int writeTransPose(std::string path, std::vector<double> pose)
{
    const char* data_path = path.c_str();
    FILE *fp = NULL;
    fp =fopen(data_path,"w");
    
    fprintf(fp, "%f\n",pose[0]);
    fprintf(fp, "%f\n",pose[1]);
    fprintf(fp, "%f\n",pose[2]);
    fprintf(fp, "%f\n",pose[3]);
    fprintf(fp, "%f\n",pose[4]);
    fprintf(fp, "%f\n",pose[5]);

    fclose(fp);
    return 1;
} 


int main(int argc, char** argv)
{
    std::vector<double> pose1;
    pose1.push_back(1.1);
    pose1.push_back(2.2);
    pose1.push_back(3.3);
    pose1.push_back(4.4);
    pose1.push_back(5.5);
    pose1.push_back(6.6);
    
    writeTransPose("../cppWrite.txt", pose1);
    
    std::vector<double> pose2;
    pose2 = readRobotPose("../pythonWrite.txt");
    for (int i = 0 ; i < pose2.size(); i++)
    {
        std::cout<<"get: "<<pose2[i]<<std::endl;
    }
    return 1;
}