同一电脑python与C++进程通信——读写txt文件

21 篇文章 1 订阅

描述

在同一电脑下,有一个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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值