iOS相关技术实现

IOS调Python脚本,OC调Python代码,附demo

2019-11-28  本文已影响0人  偷的浮生整日闲

一、背景

1、公司项目要使用微信的matrix监控;
2、matrix监控的输出日志是json日志,需要使用Python去解析出程序员能看的log日志(我..TM);
3、解析这事,咱后台不想干,前端干(我..TM);
4、所以需要:--->OC调Python解析器--->Python解析器调用matrixParse.py脚本,
  输入:json文件(eg:Crash2019-11-26_13-52-24.log),输出:log日志(output.log)
5、正常的python执行命令应该为:

$ python matrixParse.py Crash2019-11-26_13-52-24.log output.log

二、上项目

1、项目目录结构:

image.png
2、liblibPython.a是由libPython项目编译出来的,GitHub上down下来的;
3、Python的目录如上图,其中脚本文件可以放在site-packages下,也可以放在沙盒里,任意;

三、上代码

        NSString* fullpath = [[NSBundle mainBundle] pathForResource:@"python" ofType:nil inDirectory:nil];
        char home[1024];
        strcpy(home, [fullpath UTF8String]);
        NSLog(fullpath);
        Py_SetPythonHome(home);//设置python运行环境位置
        Py_Initialize();
          if (Py_IsInitialized()) {
              NSLog(@"初始化环境成功");
          }
    //    PyRun_SimpleString("print 'hello'");//say hello see debug output :)
        dispatch_queue_t queue = dispatch_queue_create(0, DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSString * docunmentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)  firstObject] ;
            NSLog(@"沙盒路径------:%@",docunmentDir);
            NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"python/lib/python2.7/site-packages/matrixParse" ofType:@"py"];
//            NSString * scriptPath =[docunmentDir stringByAppendingPathComponent:@"matrixParse.py"];//也可将python脚本放在沙盒里
            NSString *logPath = [[NSBundle mainBundle] pathForResource:@"python/lib/python2.7/site-packages/Crash2019-11-26_13-52-24" ofType:@"log"];//输入
             //NSString * logPath=[docunmentDir stringByAppendingPathComponent:@"Crash2019-11-26_13-52-24.log"];//也可用沙盒路径作为输入输出
            NSString * outputPath=[docunmentDir stringByAppendingPathComponent:@"output.log"];//输出
            FILE *mainFile = fopen([scriptPath UTF8String], "r");
            PyEval_InitThreads();
            char *argv[] = {[logPath UTF8String],[outputPath UTF8String]};//执行脚本的参数
            PySys_SetArgv(2, argv);//PySys_SetArgv的参数解释:参数1:要输入参数的个数,参数2:参数数组
            int runResult=PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]);//执行脚本
            Py_Finalize();
            NSLog(@"python脚本运行返回:%d----输出路径------:%@",runResult,outputPath);
        });

四、上demo

https://github.com/Sijia-NR/OCInvokePython

上一篇下一篇

猜你喜欢

热点阅读