2014-01-29 110 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。 –