Cocoa 应用无法开始循环 python 脚本。在 built/run 到 xcode 时有效

Cocoa app cannot start looping python script. Works when built/run through xcode

我正在尝试使用 NSTask 从 cocoa 应用启动循环 python 脚本。 python 脚本最终位于应用程序的 Contents/Resources 文件夹中。

我得到了脚本的路径并创建了 NSTask:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:filename ofType:@"py"];
    NSTask* task = [[NSTask alloc] init];
    task.launchPath = PYTHON_PATH;
    task.arguments = [NSArray arrayWithObjects:scriptPath, nil];
    [task launch];
    [task waitUntilExit];
});

(为了便于阅读,我省略了 stdOutPipe 内容)

当我从 xcode 构建和 运行 我的应用程序时,它按预期工作,任务保持在 waitUntilExit 和 python 脚本 运行s不断地。

当我尝试从生成的 .app 文件中 运行 时,它到达 waitUntilExit,暂停一段时间,然后退出并出现错误。我已经登录 python 脚本,所以我知道这段时间脚本的任何部分都不是 运行。脚本路径与 python 脚本和 returns 相同的路径,当 运行 来自 xcode 或来自 .app.

我想我一定有一些项目设置设置不正确,但它似乎正确地处理了资源。任何的想法?

更新 1 运行 一个只有打印语句的非循环 python 脚本适用于 .app。以下非循环脚本也会失败:

#!/usr/bin/python      
import os

def log(string):
    print(string)
    path = os.environ['PWD'] + '/smoke_screen_test.txt'
    f1=open(path, 'a')
    f1.write(string + "\n")

if __name__ == '__main__':
    log("Test works")
    exit(0)

也许导入语句搞砸了?还是文件创建?

问题出在 os.environ['PWD'] 的使用上。 PWD 不return 正在执行的脚本的本地目录。呃。解决方案是从 argv[0] 中获取脚本的路径并使用该路径的目录:

path = os.path.dirname(sys.argv[0])

然后根据需要传递路径。