安装ios的python解释器
https://github.com/pybee/Python-iOS-support/releases
下载之后有两个framework文件夹,供后面使用
创建ios项目
新建Cocoa Touch Class
将下载好的两个框架文件夹链接进项目中
创建PythonEnvironment.bundle
之后将Python.framework添加进bundle中
之后编写代码
PythonRunner.m
#import "PythonRunner.h"
#import <Python/Python.h>
@implementation PythonRunner
+(Boolean)run{
BOOL isEvn = [self configPythonEnvironment];
if(!isEvn){
return false;
}
[PythonRunner p_setupHomePath];
Py_Initialize();
//run simple python code
PyRun_SimpleString("print ('hello')");//say hello see debug output :)
return true;
}
+ (void)p_setupHomePath {
const char * frameworkPath = [[NSString stringWithFormat:@"%@/Resources",[self p_pythonFrameworkPath]] UTF8String];
wchar_t *pythonHome = _Py_char2wchar(frameworkPath, NULL);
Py_SetPythonHome(pythonHome);
}
+ (NSString*)p_pythonFrameworkPath{
NSString *documantPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
NSString *newFrameworkPath = [documantPath stringByAppendingPathComponent:@"Python.framework"];
return newFrameworkPath;
}
+ (BOOL)configPythonEnvironment
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *bundlePath = [mainBundle pathForResource:@"PythonEnvironment" ofType:@"bundle"];
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:bundlePath];
if(!isExist) {
return NO;
}
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
NSString *PythonPath = [bundle pathForResource:@"Python" ofType:@"framework"];
isExist = [[NSFileManager defaultManager] fileExistsAtPath:PythonPath];
if (!isExist) {
return NO;
}
NSString *newFrameworkPath = [self p_pythonFrameworkPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:newFrameworkPath]) {
return YES;
}
NSError * error;
[[NSFileManager defaultManager] copyItemAtPath:PythonPath toPath:newFrameworkPath error:&error];
if (error) {
return NO;
}
return YES;;
}
@end
PythonRunner.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PythonRunner : NSObject
+(Boolean)run;+ (void)p_setupHomePath;+ (BOOL)configPythonEnvironment;
@end
NS_ASSUME_NONNULL_END
main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "PythonRunner.h"
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
PythonRunner.run;
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
build
失败
添加链接库
再次build
成功
另:运行.py文件
在项目中创建py文件
编写测试代码
a=1
b=2
c=a+b
print(c)
print("hello")
在PythonRunner.m的run函数中添加如下代码
dispatch_queue_t queue = dispatch_queue_create(0, DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
//run python scipt
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"py"];
FILE *mainFile = fopen([scriptPath UTF8String], "r");
PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]) ;
});