// Run a command
+(NSString*)runCommand:(NSString*)cmd {
// Create an empty string
NSMutableString* mutableString = [NSMutableString stringWithCapacity:0];
// Create a thread pool
NSAutoreleasePool *threadPool = [[NSAutoreleasePool alloc] init];
// Create a new task
NSTask *task = [[NSTask alloc] init];
// Configure the task
[task setStandardOutput: [NSPipe pipe]];
[task setStandardError: [task standardOutput]];
[task setLaunchPath:cmd];
// Launch the task
[task launch];
// Append the output
NSData *data;
while ((data = [[[task standardOutput] fileHandleForReading] availableData]) && [data length]) {
NSString* output = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
[mutableString appendString:output];
}
// Make sure the task is finished
[task terminate];
// Release the thread pool
[threadPool release];
// Return the output
return mutableString;
}
本文提供了一个使用Objective-C来执行外部命令并获取其输出的示例代码。通过创建任务并配置标准输入输出,该方法能够捕获命令执行后的所有输出。
3508

被折叠的 条评论
为什么被折叠?



