2014-01-29 44 views
0

如何以編程方式運行終端命令?可可應用程序 - NSTask

現在我在做這樣的:

-(IBAction)proceedTapped:(id)sender 
{ 
NSLog(@"%@",[self runCommand:@"cd ~"]); 
NSLog(@"%@",[self runCommand:@"ls"]); 
} 

-(NSString *)runCommand:(NSString *)commandToRun 
{ 
NSTask *task = [[NSTask alloc] init]; 
[task setLaunchPath: @"/bin/sh"]; 
NSArray *arguments = [NSArray arrayWithObjects: 
         @"-c" , 
         [NSString stringWithFormat:@"%@", commandToRun], 
         nil]; 

[task setArguments: arguments]; 

NSPipe *pipe; 
pipe = [NSPipe pipe]; 
[task setStandardOutput: pipe]; 

NSFileHandle *file; 
file = [pipe fileHandleForReading]; 


[task launch]; 


NSData *data; 
data = [file readDataToEndOfFile]; 

NSString *output; 
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 
return output; 
} 

對於單命令該代碼工作得很好,但對我來說,當我想改變目錄 到〜(家),然後做「LS」這不起作用(它看起來像在兩個不同的終端窗口中運行兩個命令)。 那麼如何在一個終端窗口中運行多個命令? 謝謝。

+1

可能重複[如何在循環中使用NSTask運行終端命令在一致的環境?](http://stackoverflow.com/questions/13217415/how-to-use-nstask-run-terminal-commands-in-循環在一致的環境) –

+0

按照這個http://stackoverflow.com/questions/19038364/nsprocessinfo-returns-different-path-than-echo-path/19050417#19050417 –

回答

0

在我的應用我有: -

- (IBAction)openDirInTerminal:(id)sender { // context only 
    DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem]; 
    NSString *s = [NSString stringWithFormat: 
        @"tell application \"Terminal\" to do script \"cd \'%@\'\"", item.fullPath]; 
    NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s]; 
    [as executeAndReturnError:nil]; 
} 

DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem];是我的方法,但其路徑替換item.fullPath

您可以將第二個命令添加到腳本字符串(後跟一個換行符)。

+0

你所做的是使用applescript。這不是詢問者想要使用unix shell腳本的人。按照這個http://stackoverflow.com/questions/19038364/nsprocessinfo-returns-different-path-than-echo-path/19050417#19050417。 –

+0

@HussainShabbir:嗯,它使用AppleScript來運行一個shell腳本... – mipadi

+0

他想使用NSTask而不是NSApplescript。 –