从 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
"的例子.
You can use NSTask
. Here's an example that would run '/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:
%@", 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;
解释在这里:https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask
这篇关于从 Cocoa 应用程序执行终端命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!