如何执行终端命令(例如grep
)来自我的 Objective-C Cocoa 应用程序?
您可以使用NSTask http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTask_Class/Reference/Reference.html
。这是一个运行的示例 '/usr/bin/grep foo bar.txt
'.
int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);
NSPipe
and NSFileHandle
用于重定向任务的标准输出。
有关在 Objective-C 应用程序中与操作系统交互的更多详细信息,您可以在 Apple 开发中心查看此文档:与操作系统交互 http://developer.apple.com/documentation/Cocoa/Conceptual/OperatingSystem/OperatingSystem.html#//apple_ref/doc/uid/10000058.
编辑:包含 NSLog 问题的修复
如果您使用 NSTask 通过 bash 运行命令行实用程序,那么您需要包含此神奇行以保持 NSLog 正常工作:
//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
解释在这里:https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)