XcodeiOS实用功能

Xcode调用python脚本

2018-05-04  本文已影响0人  悄然林静

OC

-(id) InvokingPythonScriptAtPath :(NSString*) pyScriptPath
{
    // 创建task
    NSTask *pythonTask = [[NSTask alloc]init];
    [shellTask setLaunchPath:@"/bin/bash"];
    NSString *pyStr = [NSString stringWithFormat:@"python %@",pyScriptPath];
    
    [shellTask setArguments:[NSArray arrayWithObjects:@"-c",pyStr, nil]];
    
    //创建输出管道 
    NSPipe *pipe = [[NSPipe alloc]init];
    [shellTask setStandardOutput:pipe];
    
    // 开启task
    [shellTask launch];
    
    NSFileHandle *file = [pipe fileHandleForReading];
    NSData *data =[file readDataToEndOfFile];
    NSString *strReturnFromPython = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"The return content from python script is: %@",strReturnFromPython);
    
    return strReturnFromPython;
}

Swift

   /// 运行脚本
    func runScript() {
        // Swift调用终端用Process类,这里先创建一个对象
        let pro = Process()
        
        // 指定编译器
        pro.launchPath = "/bin/bash"

        // 设置要执行的语句,如果是有多条命令,用;隔开
        // 注意!因为命令是用""包在字符串里的,所以命令中有"时要用\"做转义
        pro.arguments = ["-c", "pwd; which python; python -V; python test01.py; say start; pwd; which python3; python3 -V; python3 test03.py; python3 TestWYY.py; say over"]
        
        // 启动
        pro.launch()
        pro.waitUntilExit()
        
        print("脚本执行完毕")
    }
    这里有个遗留问题,Mac系统(10.13.4)自带的python版本是2.7.10,如果python3是用HomeBrew安装的,那么python3 xxxx.py会报错command not found,个人推测可能是因为Xcode默认调用的是系统自带的python2.7.10。
    关于Mac上各版本python所在的具体路径,详见我的另一篇文章:https://www.jianshu.com/p/6a129afc734b
上一篇下一篇

猜你喜欢

热点阅读