从Cocoa应用程序执行终端命令 [英] Execute a terminal command from a Cocoa app
问题描述
如何从我的Objective-C Cocoa应用程序执行终端命令(如 grep
)?
How can I execute a terminal command (like grep
) from my Objective-C Cocoa application?
推荐答案
您可以使用 NSTask
。这里有一个例子,运行 / 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
NSFileHandle 用于重定向任务的标准输出。
NSPipe
and NSFileHandle
are used to redirect the standard output of the task.
有关在Objective-C应用程序中与操作系统交互的更多详细信息,您可以在Apple开发中心查看此文档:与操作系统交互。
For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: Interacting with the Operating System.
编辑:包含NSLog问题的修复
Included fix for NSLog problem
如果您使用NSTask运行命令行实用程序bash,那么你需要包含这个魔术线来保持NSLog的工作:
If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:
//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
解释在这里: http://cocoadev.com/HowToPipeCommandsWithNSTask
这篇关于从Cocoa应用程序执行终端命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!