我正在尝试从Cocoa应用程序中运行Python脚本。它在主线程上运行得很好,但是我想让它在后台、并发的GCD队列上运行。
我正在使用以下方法设置一个管理器类来运行Python脚本:
- (BOOL)setupPythonEnvironment {
if (Py_IsInitialized()) return YES;
Py_SetProgramName("/usr/bin/python");
Py_Initialize();
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"MyScript" ofType:@"py"];
FILE *mainFile = fopen([scriptPath UTF8String], "r");
return (PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]) == 0);
}
此后,脚本将从以下实例方法中被(重复)调用,使用管理器类的共享单例实例:
- (id)runScriptWithArguments:(NSArray *)arguments {
return [NSClassFromString(@"MyScriptExecutor") runWithArguments:arguments];
}
上述Objective-C代码插入到以下Python代码中:
from Foundation import *
def run_with_arguments(arguments):
# ...a long-running script
class MyScriptExecutor(NSObject):
@classmethod
def runWithArguments_(self, arguments):
return run_with_arguments(arguments)
当我总是从主队列运行上述Objective-C方法时,它可以正常工作,但是当从其他队列运行时,脚本会返回null。是否有人能够解释一下,我想做的事情是否不受支持,以及是否有好的解决方法?
由于Python脚本经常被调用并且运行时间较长,因此在主线程上执行将会很慢,所以我将在串行队列中运行它。此外,我希望尽可能将并发代码包含在Objective-C中。
谢谢。