2013-10-04 74 views
0

我有一個可可應用程序,我想啓動一個啓動Node.js的shell腳本。我想我會這樣做與NSTask使用NSTask啓動啓動Node.JS的shell腳本

NSTask *task = [[NSTask alloc] init]; 
[task setLaunchPath:@"/bin/bash/start.sh"]; 
[task setArguments:[NSArray arrayWithObjects:@"start.sh", nil]]; 
[task setStandardOutput:[NSPipe pipe]]; 
[task setStandardInput:[NSPipe pipe]]; 

[task launch]; 

腳本是在我的應用程序的根。我嘗試了很多發射路徑的變化,並且我被卡住了。任何幫助將不勝感激!

編輯:

這裏是我的新代碼,我設置參數。由於某些原因,它仍然不起作用。

NSTask *task = [[NSTask alloc] init]; 
[task setLaunchPath:@"/bin/bash"]; 
[task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"start" ofType:@"sh"], nil]]; 
[task launch]; 

回答

2

正如您猜測的那樣,問題在於您的發射路徑。

啓動路徑必須是單個文件路徑。文件名將不起作用*,並且不能在同一路徑中命名兩個單獨的文件。

您的啓動路徑應該是bash的完整絕對路徑。在終端中使用which bash找出哪一個。 (它應該是/ bin/bash在股票OS X安裝上。)

要告訴bash運行腳本,您需要在參數中標識它。只是說劇本的名字不會削減它;你必須給腳本完整的絕對路徑。沒有理由將腳本的文件名放在任何地方。

我假設腳本是你的應用程序包中的一個資源。要獲得它的絕對路徑,請詢問your main bundle,獲取the URL to that resource,然後get that URL's path。如果你需要一個具體的優點,這個基於URL的方法可以正確地調用它的第二個參數的文件擴展名,而不是一個「類型」;「你可以直接詢問a path for a resource,但是使用URL是一個值得開發的習慣。類型「意味着在現代使用中有所不同)


*文件名被視爲任何其他相對路徑。相對路徑可以運行,但需要解析爲相對於當前工作目錄存在的路徑。默認情況下,這是/(根目錄),所以任何可以工作的相對路徑在功能上等同於絕對路徑。你應該在任何地方使用絕對路徑。

+0

我編輯我的答案,我設置參數和更改路徑。它仍然無法工作。 –

+0

pathForResource:我認爲它是錯誤的。這些文檔讓我很難理解如何獲得正確的路徑。 –

+1

@MinaDawoud:以什麼方式? –

0

我有這個完全相同的問題,這就是我解決它的方法。假設您使用的是捆綁應用程序,那麼您可以向NSBundle詢問應用程序可執行文件的路徑。如果你的腳本與可執行文件在同一個目錄下(<name>.app/Contents/MacOS/),那麼這應該起作用。

NSString *wd = [[NSBundle mainBundle] executablePath]; 
// this creates a path to <name.app>/Contents/MacOS/<name>/../script, where <name> 
// is the name of your app's executable file 
NSString *path = @"/../script"; 
NSString *fullPath = [wd stringByAppendingString: path ]; 

[scriptTask setLaunchPath: fullPath]; 
[scriptTask launch]; 
0

你應該試試這個:

NSString *path = [[NSBundle mainBundle] pathForResource:@"SCRIPT_NAME" ofType:@"sh"]; 
NSString *commandToRun =[NSString stringWithFormat:@"/usr/bin/osascript -e\ 
         'do shell script \"%@ args 2>&1 etc\" with administrator\ 
         privileges'",path]; 
NSArray *arguments = [NSArray arrayWithObjects: 
         @"-c" , 
         [NSString stringWithFormat:@"%@", commandToRun], 
         nil]; 
[task setLaunchPath:@"/bin/sh"]; 
[task setArguments:arguments]; 

[task launch]; 
[task waitUntilExit];    // wait for completion 
if ([task terminationStatus] != 0) // check termination status 
{ 
    NSLog(@"termination status is %d",[task terminationStatus]); 

} 

如果terminationStatus = 0,沒有與任務的問題!有什麼不對,你應該檢查腳本。