1

我为没有GUI的Mac OS创建了命令行应用程序。该应用程序位于/ usr/local/bin。在某些情况下,我需要在该应用程序中执行Apple Script。要做到这一点,我创建一个NSTask,并试图运行下面的命令:它运行后,没有任何反应,只有在日志中出现的消息无法从命令行应用程序运行Apple脚本

NSTask *createTask = [[NSTask alloc] init]; 
    createTask.launchPath = @"/bin/bash"; 
    NSString *showAlert = [NSString stringWithFormat:@"/usr/bin/osascript -e 'tell application \"Finder\" to display alert \"My text.\"'"]; 
    NSArray *arguments = [NSArray arrayWithObjects:@"-c",showAlert, nil]; 
    createTask.arguments = arguments; 
[createTask launch]; 

Apr 14 15:35:15 Mac-mini kernel[0]: my-app: guarded fd exception: fd 0 code 0x2 guard 0x7fff8b9e12a8 
Apr 14 15:35:15 Mac-mini com.apple.xpc.launchd[1] (com.apple.ReportCrash.Root[26852]): Endpoint has been activated through legacy launch(3) APIs. Please switch to XPC or bootstrap_check_in(): com.apple.ReportCrash.DirectoryService 
Apr 14 15:35:15 Mac-mini diagnosticd[16097]: error evaluating process info - pid: 26851, punique: 26851 
Apr 14 15:35:16 Mac-mini sandboxd[16099] ([26851]): my-app(26851) deny file-read-data/

但是,如果你运行此命令直接从终端,它被正确执行。请告诉我,我做错了什么?

+0

我有一个暗示'NST问'会使用运行循环。你如何管理程序中的运行循环? – trojanfoe

+0

看来我没有使用运行循环管理。你能建议我应该尝试吗? – Emmett

+0

我不认为它实际上与您的问题有关,但是如果您使用的是Foundation框架,那么您确实需要大量的运行循环。我有一个简单的[RunLoopController](https://github.com/trojanfoe/RunLoopController)用于命令行,您可能会发现它很有帮助。 – trojanfoe

回答

0

我认为这个问题可能与您使用引号有关。当我尝试在shell中用引用样式手动运行相同的命令时,它将不起作用。我在下面的例子工作。你可以切换你的单引号和双引号吗?使用单引号加密您的初始调用,然后在osascript周围使用双引号?另外,不需要使用tell application \"Finder\" to,因为显示警报不是Finder字典的一部分。

你...

/usr/bin/osascript -e 'tell application \"Finder\" to display alert \"My text.\"' 

尝试将其更改为...

​​

或者更简单的版本...

osascript -e "display alert \"My text.\"" 
+0

我认为问题不在语法中。因为如果我从终端运行我的应用程序线程应用程序,那么一切正常。但在这种情况下,我的命令行应用程序由另一个应用程序(驱动程序)调用,而不是来自主线程。 – Emmett