在我的 Mac OS 应用程序中,我包含了一个 Python.framework (v 2.7),所以我根据需要将它添加到“链接框架”中。同样在应用程序中,我正在使用 NSTask 启动一个 Python 脚本,例如:
//...
pythonEnv = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"Python.framework/Versions/2.7/bin/python"];
task = [[NSTask alloc] init];
outPipe = [NSPipe pipe];
readHandle = [outPipe fileHandleForReading];
data = [[NSMutableData alloc] init];
args = [NSArray arrayWithObjects: scriptPath, kbt, server, port, username, password, nil];
[task setArguments:args];
[task setLaunchPath: pythonEnv];
readHandle = [outPipe fileHandleForReading];
[task setStandardInput:[NSPipe pipe]];
[task setStandardOutput:outPipe];
[task launch];
[task waitUntilExit];
//...
当我构建应用程序并在 Python 脚本中检查它使用的版本时sys.path
,它会返回:
["/Users/...脚本的路径.../Contents/Resources", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip", "/Library/Frameworks/Python.framework /Versions/2.7/lib/python2.7", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin", "/Library/Frameworks/Python.framework/Versions/2.7 /lib/python2.7/plat-mac", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages", "/Library/Frameworks/Python.framework /Versions/2.7/lib/python2.7/lib-tk”、“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old”、“/Library/Frameworks/Python.framework /Versions/2.7/lib/python2.7/lib-dynload", "/Users/tatiana/Library/Python/2.7/lib/python/site-packages", "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages", "/Library/Python/2.7/site-packages"]
...它没有使用我包含的框架。我还应该在哪里设置正确的路径?我忘记了构建设置中的内容吗?
更新 1 ---------------------
如果我没有设置任务环境,并且在 Python 测试中sys.executable
,我得到:
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
...所以看起来它没有使用我的框架。如果设置任务环境:
// pythonEnv = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"Python.framework/Versions/2.7/bin/python"];
NSDictionary *environment = [NSDictionary dictionaryWithObjectsAndKeys: pythonEnv, @"PYTHONPATH", nil];
[task setEnvironment:environment];
并测试它,我仍然得到相同的结果。但是,如果在 Python 中我用 测试os.environ["PYTHONPATH"]
,我得到:
/Users/tatiana/Desktop/MyApp.app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python
这看起来更有希望,但我很困惑为什么 sys.executable 没有给我这个。
更新 2
我的bin/python不是可执行文件,所以我将其更改为 python2.7;sys.executable
仍然显示它默认为 Library/...
pythonEnv = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"Python.framework/Versions/2.7/bin/python2.7"];
NSString *searchPath = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"Python.framework/Versions/2.7/lib/python2.7"];
NSDictionary *environment = [NSDictionary dictionaryWithObjectsAndKeys: searchPath, @"PYTHONPATH", nil];
[task setEnvironment:environment];