【发布时间】:2015-03-04 20:33:55
【问题描述】:
我一直在努力尝试从 Objective-C 中运行一个 Applescript,该 Applescript 向终端查询以运行一些 shell 命令。我遇到了如何在 Objective-C 中格式化命令的问题,以便正确引用脚本对象。
这就是脚本看起来像一个applescript
set thisFile to "Dev1.4"
set testTarget to "/Users/lab/Desktop/untitled"
do shell script "/Users/lab/Desktop/TempRoot/myCommand.command " & thisFile & space & testTarget with administrator privileges
此脚本已在我之前关于将多个命令从 applescript 文件传递到终端命令文件 (Passing Multiple Parameters from Applescript to Terminal Command Script) 的问题中进行了测试和验证。
我的 Objective-C 编码尝试如下:
NSObject *arrayObj = arguments[0];
NSString *tmpString1 = [arguments objectAtIndex:0];
NSString *tmpString2 = [arguments objectAtIndex:1];
NSString * fullScript = [NSString stringWithFormat:@"'%@' & get quoted form of %@ & space & get quoted form of %@", scriptPath, tmpString1, tmpString2];
NSDictionary *errorInfo = [NSDictionary new];
NSString *script = [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];
NSLog(script);
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];
如果有人能告诉我如何正确格式化创建完整脚本的这一行,那将不胜感激!
NSString * fullScript = [NSString stringWithFormat:@"'%@' & get quoted form of %@ & space & get quoted form of %@", scriptPath, tmpString1, tmpString2];
如果您有任何问题,或者需要更多信息,请告诉我。
----------------------------------------------- ----------------------------------
----------------------------------------------- ----------------------------------
编辑:
我发现了一些关于该问题的新信息。似乎@ShooTerKo 的回答解决了语法问题。然而,导致applescript失败的原因是Applescript中无法识别文件路径,因为applescript不喜欢它的文件路径名中的空格。
例如:
set testTarget to "/Users/lab/Desktop/Problem Folder"
set thisFile to "Dev1.4"
do shell script "/Users/lab/Desktop/TempRoot/myCommand.command " & thisFile & space & testTarget with administrator privileges
将导致applescript只保存
“/Users/lab/Desktop/Problem”
作为变量,因此无法获得正确的路径。这可以在我的调试模式中找到,并出现以下错误:
Printing description of errorDescription->*errorDescription:
/bin/sh: /Users/lab/Library/Developer/Xcode/DerivedData/Branch_Copier_GUI-fqaphewyolyltbehjgtknknowmrr/Build/Products/Debug/Branch: No such file or directory
我将考虑重命名我的项目以包含下划线,以便由 applescript 更恰当地解释,并对这个新错误进行更多研究。再次感谢您的帮助,我真的很感激!
【问题讨论】:
-
嗯,如果使用我的解决方案,空格应该不是问题,它们应该正确地传递给 shell 脚本。问题可能发生在
myCommand.command内部以及那里如何处理给定路径! -
@ShooTerKo 没错,您的空间解决方案运行良好!路径中也可能出现第二个问题,但是,当前的问题是我的文件路径由于文件路径中的空格而被截断(Applescript 截断了带有空格的文件路径,如上所示)
-
不要通过字符串混搭来生成代码。这是邪恶和错误的。 网络上永无止境的 SQL 注入攻击扩散就是证明。如果您必须使用
NSAppleScript,例如要运行用户提供的脚本,请使用-executeAppleEvent:error:将任何变量作为参数传递给脚本 (appscript.sourceforge.net/nsapplescript.html)。或者,如果 AppleScript 代码是您的应用程序的一部分,只需通过 AppleScript-ObjC 桥 (appscript.sourceforge.net/asoc.html) 从您的 ObjC 代码直接调用其处理程序。
标签: objective-c scripting format applescript applescript-objc