工作中那些比较,通用的脚本和工具

2022-12-04 16:20:04 浏览数 (1)

分享一些工作中常用的脚本工具~

1,Bag包的合并

2,CallBack的使用

3,#define 中声明类

4,获取当前进程PID

5,C调用shell返回结果

6,根据指定字符分割字符串

7,统计文本文件时间戳

一,rosBag的合并

代码语言:javascript复制
#!/usr/bin/env python
import sys
import argparse
from fnmatch import fnmatchcase
 
from rosbag import Bag

def main():
 
    parser = argparse.ArgumentParser(description='Merge one or more bag files with the possibilities of filtering topics.')
    parser.add_argument('outputbag',
                        help='output bag file with topics merged')
    parser.add_argument('inputbag', nargs=' ',
                        help='input bag files')
    parser.add_argument('-v', '--verbose', action="store_true", default=False,
                        help='verbose output')
    parser.add_argument('-t', '--topics', default="*",
                        help='string interpreted as a list of topics (wildcards '*' and '?' allowed) to include in the merged bag file')
 
    args = parser.parse_args()
 
    topics = args.topics.split(' ')
 
    total_included_count = 0
    total_skipped_count = 0
 
    if (args.verbose):
        print("Writing bag file: "   args.outputbag)
        print("Matching topics against patters: '%s'" % ' '.join(topics))
 
    with Bag(args.outputbag, 'w') as o: 
        for ifile in args.inputbag:
            matchedtopics = []
            included_count = 0
            skipped_count = 0
            if (args.verbose):
                print("> Reading bag file: "   ifile)
            with Bag(ifile, 'r') as ib:
                for topic, msg, t in ib:
                    if any(fnmatchcase(topic, pattern) for pattern in topics):
                        if not topic in matchedtopics:
                            matchedtopics.append(topic)
                            if (args.verbose):
                                print("Including matched topic '%s'" % topic)
                        o.write(topic, msg, t)
                        included_count  = 1
                    else:
                        skipped_count  = 1
            total_included_count  = included_count
            total_skipped_count  = skipped_count
            if (args.verbose):
                print("< Included %d messages and skipped %d" % (included_count, skipped_count))
 
    if (args.verbose):
        print("Total: Included %d messages and skipped %d" % (total_included_count, total_skipped_count))
 
if __name__ == "__main__":
    main()

二,CallBack的使用

代码语言:javascript复制
using FunACallback = std::function<int(const std::string)>;
using FunBCallback = std::function<double(const int)>;

typedef struct Callbacks
{
    FunACallback funacallback;
    FunBCallback funbcallback;
}CALLBACKS;

Callbacks     m_callbacks;

bool callbackRegister(const Callbacks& callbacks)
{
    m_callbacks.funacallback = callbacks.funacallback;
    m_callbacks.funbcallback = callbacks.funbcallback;

    return true;
}

int FunA(const std::string str_)
{   
    //可以连接到其他函数接口

    std::cout<<"FUNA: "<<str_<<std::endl;
    return 1;
}

double FunB(const int str_)
{   
    std::cout<<"FUNB: "<<str_<<std::endl;
    return 1.0;
}

bool Init()
{
    Callbacks callbacks;
    callbacks.funacallback = std::bind(&FunA,std::placeholders::_1);
    callbacks.funbcallback = std::bind(&FunB,std::placeholders::_1);

    callbackRegister(callbacks);

    return true;
}

bool Process()
{
    m_callbacks.funacallback("lililili");
    m_callbacks.funbcallback(1);
}



int main()
{
    Init();
    Process();
}

三,#define 中声明类

代码语言:javascript复制
class Base {
public:
    virtual void f() {
        std::cout << "this is Base";
    };
};
class A : public Base {
public:
    void f() {
        std::cout << "this is A";
    }
};

typedef std::shared_ptr<Base> (*CreatefeedFunction)();
typedef std::unordered_map<std::string, CreatefeedFunction> feedMap;
feedMap g_feed_map;

#define REGISTER_DATAFEED_CLASS(feed_class)                        
namespace {                                                        
std::shared_ptr<Base> Creator_##feed_class() {                     
    return std::shared_ptr<Base>(new feed_class);                  
}                                                                  
class __Registerer_##feed_class {                                  
public:                                                            
    __Registerer_##feed_class() {                                  
        g_feed_map[#feed_class] = &Creator_##feed_class;           
    }                                                              
};                                                                 
__Registerer_##feed_class g_registerer_##feed_class;                
} // namespace                                                     

REGISTER_DATAFEED_CLASS(A); // 函数体内部不能进行函数的定义
int main()
{
    std::shared_ptr<Base> p = g_feed_map["A"]();
    p->f();
 return 0;
}

四,通过名字获取当前进程PID

代码语言:javascript复制
pid_t getProcessPidByName(const char *proc_name)
{
     FILE *fp;
     char buf[100];
     char cmd[200] = {''};
     pid_t pid = -1;
     sprintf(cmd, "pidof %s", proc_name);
 
     if((fp = popen(cmd, "r")) != NULL)
     {
         if(fgets(buf, 255, fp) != NULL)
         {
             pid = atoi(buf);
         }
     }
 
     printf("pid = %d n", pid);
 
     pclose(fp);
     return pid;
}
int main(int argc, char** argv)
{
    if(argc != 2)
    {
        printf("Invalid input! n");
        return -1;
    }
    char* process_name = argv[1];
 
    pid_t process_pid = getProcessPidByName((const char*)process_name);
 
    return 0;
}

五,C 调用shell指令并返回结果

代码语言:javascript复制
static bool executeCmd(const char* cmd, char* pReturns)
{
    FILE *ptr;
    char command[1024] = {0};
  
    snprintf(command, sizeof(command), cmd);
    ptr = popen(command, "r");
    
    std::string work_path = getcwd(NULL, 0);
    std::cout<<"current patch is "<<work_path<<"command: "<<command<<std::endl;

    if(NULL != ptr)
    {
        if(NULL != pReturns)
        {
            int rv = -1;
            char result_buf[1024] = {0};
            if((rv = std::fread(result_buf, 1, sizeof(result_buf), ptr)) < 0)
            {
                return false;
            }
            else
            {
                strcat(pReturns, result_buf);
            }
            std::cout<<"result_buf is "<<pReturns<<std::endl;
        }
        int rc = pclose(ptr);
    }
    else
    {
        return false;
    }

    return true;
}

int main()
{    
    char ans[1024] = {0};
    std::string cmd = "ls";
    
    if(!executeCmd(cmd.c_str(), ans))
    {  
        return false;
    }
}

六,根据指定字符分割字符串

代码语言:javascript复制
void spiltStr(std::string str,const std::string & split,std::vector<std::string>&strlist)
{
    strlist.clear();
    if(str=="")
        return;
    std::string strs=str split;
    size_t pos=strs.find(split);
    int steps=split.size();

    while(pos!=strs.npos)
    {
        std::string temp=strs.substr(0,pos);
        strlist.push_back(temp);
        strs=strs.substr(pos steps,strs.size());
        pos=strs.find(split);
    }
}

int main()
{
    std::string conf_path = "$(arg config_file_path)/0,$(arg config_file_path)/1,$(arg config_file_path)/2,$(arg config_file_path)/3,$(arg config_file_path)/fisheye";

    std::vector<std::string> str_1_1;
    std::vector<std::string> str_2_2;
    spiltStr(conf_path,",",str_1_1);
    
    std::cout<<"size: "<<conf_path.size()<<std::endl;

    for (auto i: str_1_1)
    {
        std::cout<<"str_1: "<<i<<std::endl;
    }
}

七,脚本统计文本文件时间戳

代码语言:javascript复制
import codecs
from numpy import *

import matplotlib.pyplot as plt
import numpy as np

f = codecs.open('track.txt', mode='r', encoding='utf-8')  
line = f.readline()   
time_detect = []
while line:
    time_d = line.split('cost time = ')[1]
    time_d = time_d.split(' ')[0]
    # print(time_d)
    # print(type(time_d))
    time_detect.append(float(time_d))
        
    line = f.readline()
f.close()

time_detect = sorted(time_detect)
max_time_t4_t3 = max(time_detect)
min_time_t4_t3 = min(time_detect)
mean_time_t4_t3 = mean(time_detect)
len_time_t4_t3 = len(time_detect)
tp_99_time_t4_t3 = time_detect[int(len_time_t4_t3 * 0.99)]
tp_50_time_t4_t3 = time_detect[int(len_time_t4_t3 * 0.5)]

print("len: ",len_time_t4_t3)
print("max: ",max_time_t4_t3)
print("min: ",min_time_t4_t3)
print("mean: ",mean_time_t4_t3)
print("tp_99: ",tp_99_time_t4_t3)
print("tp_50: ",tp_50_time_t4_t3)

0 人点赞