Python在iOS中的运用示例

iOS如何使用Python步骤

#include “Python.h"

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//init python

//get python lib path and set this path as python home directory

NSString* fullpath = [[NSBundle mainBundle] pathForResource:@"python" ofType:nil inDirectory:nil];

char home[1024];

NSLog(@"%@",fullpath);

strcpy(home, [fullpath UTF8String]);

Py_SetPythonHome(home);

Py_Initialize();

//执行python语句

PyRun_SimpleString("print 'hello'");//say hello see debug output :)

PyRun_SimpleString("print 'cathy'");//say hello see debug output :)

dispatch_queue_t queue = dispatch_queue_create(0, DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{

//执行python脚本

NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"python"    ofType:@“py"];

//从文件中读取要执行的代码

FILE *mainFile = fopen([scriptPath UTF8String], "r");

PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]) ;

});

return YES;

}


标注1:

NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"python"    ofType:@“py"];

这句代码指的是下图1的路径下的python.py。

以下为该文件的代码

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import socket

print "This is a beautifulcathy"

图1


如图2所示

1.要在项目中执行python语句需要另一个工程的加入,

libPython.xcodeproj

即,一个工程加入另一个工程。

图2

二.知识点:一个工程加入另一个工程。

1.需要将两个工程放在同一级

目录下,如图3,导入

即是将后缀为 .xcodeproj 文件像一般添加文件到目标工程那样。

2.如图3

-1:项目是将libPython工程导入到trypythonagain 工程中。

-2:将python 这个重要的文件也要放在工程的同一级目录下。(不可缺的一个文件)


图3

-3:python 文件的引入

1).添加一个group,名为Bundles

图4

2).拖python文件到Bundles目录下

拖时注意勾选如图5

图5

3.一个工程导入另一个工程需要引入一些静态库

如图6

图6

point:liblibPython.a 是libPython(被导入到目标工程的子工程)的工程包。点击+ 时搜索lib 就可出现了。

4.遇到的问题

说找不到这个文件

图7


但是在子工程下明明有,

为什么找不到呢  如图8

图8


原因是:找不到子工程的目录

需要在Build Settings 中引入子工程的文件的目录。

图9

好了,现在大功告成了。在工程中执行了Python 语句

图10

下载链接: https://pan.baidu.com/s/1slr0kZr 密码: y98p

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容