iOS开发之调用python脚本

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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值