如何以编程方式运行终端命令?可可应用程序 - 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”这不起作用(它看起来像在两个不同的终端窗口中运行两个命令)。 那么如何在一个终端窗口中运行多个命令? 谢谢。
可能重复[如何在循环中使用NSTask运行终端命令在一致的环境?](http://stackoverflow.com/questions/13217415/how-to-use-nstask-run-terminal-commands-in-循环在一致的环境) –
按照这个http://stackoverflow.com/questions/19038364/nsprocessinfo-returns-different-path-than-echo-path/19050417#19050417 –