簡體   English   中英

如何使用apple腳本執行cd命令

[英]How to execute cd commands with apple script

我編寫了一個程序,使用蘋果腳本在cocoapp中執行命令。 我面臨着兩個問題:1)applescript總是從projet目錄開始,而不是從root 2)cd命令正在工作,但是當我執行pwd時它顯示的是前一個目錄名而不是新目錄名。

+(BOOL)callAppleScriptForScriptFile:(NSString *)command{
    BOOL isError = YES;
NSAppleEventDescriptor* returnDescriptor = NULL;
NSDictionary* errorDict = nil;

NSString *appleScriptCommand = [NSString stringWithFormat:@"do shell script \" %@  &> /Users/username/Desktop/.output.txt\"  user name \"username\" password \"password\" with administrator privileges",command];
    //NSLog(@"Script command %@",appleScriptCommand);
NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:appleScriptCommand];


returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
if (errorDict != NULL){
    NSLog(@"%@",errorDict);
    isError = NO;
}
DescType descriptorType = [returnDescriptor descriptorType];
NSLog(@"descriptorType == %@", NSFileTypeForHFSTypeCode(descriptorType));
NSData *data = [returnDescriptor data];
double currentPosition = 0;
[data getBytes:&currentPosition length:[data length]];
NSLog(@"currentPosition == %f", currentPosition);
[self readFromFileAndSend];
return isError;

}

期待像這樣的輸出cd桌面o / p:成功(無需打印)pwd o / p:桌面

每個do shell script語句都使用一個新的shell進程,所以你不能做一些事情,比如在一個語句中更改工作目錄,然后期望它在另一個語句中是相同的。 例如,如果使用單獨的語句

do shell script "cd ~/Desktop"
do shell script "pwd"

第二個語句將顯示根目錄,因為它重新開始 - 它與第一個語句沒有任何關系。 您需要在同一語句中包含所有命令

do shell script "cd ~/Desktop; pwd"

在Cocoa應用程序中,您還可以使用NSTask,這將避免所有Apple Event事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM